Converting JSON to C# classes - json

I am trying to convert the following JSON to c# classes and I am having problems deserializing it.
{
"base": "NZD",
"end_date": "2022-08-23",
"rates": {
"2021-08-23": {
"AUD": 0.956173,
"EUR": 0.586928,
"GBP": 0.502258,
"USD": 0.6893
},
"2021-08-24": {
"AUD": 0.956925,
"EUR": 0.590177,
"GBP": 0.50541,
"USD": 0.693675
},
"2022-08-23": {
"AUD": 0.898189,
"EUR": 0.621674,
"GBP": 0.525184,
"USD": 0.616468
}
},
"start_date": "2021-08-23",
"success": true,
"timeseries": true
}
The rates I would like as a dictionary and I would also like the "AUD", "EUR", "GBP" and "USD" as a dictionary.
I have tried a few tools that I normally use like QuickType.IO but it converts the rates to
[JsonProperty("rates")]
public Dictionary<string, Rate> Rates { get; set; }
public partial class Rate
{
[JsonProperty("AUD")]
public double Aud { get; set; }
[JsonProperty("EUR")]
public double Eur { get; set; }
[JsonProperty("GBP")]
public double Gbp { get; set; }
[JsonProperty("USD")]
public double Usd { get; set; }
}
From my understanding it should probably be more like
[JsonProperty("rates")]
public Dictionary<string, Dictionary<string, double>> Rates { get; set; }
But none of these will deserialize the JSON.
I would like to use the NewtonSoft JsonConvert.DeseriableObject<> to convert the JSON text to objects.
Any thoughts?

My fault - I was deserializing using the wrong class - I was sure I checked that.
Da.
Sorry for the trouble...

Related

Parse Json response in C# using Newtonsoft.Json nuget

I have the below json response. How to read the CustomerList data from the json response. I will bind this data to a gridview. Using the Newtonsoft.Json nuget.
{
"Status": "OK",
"StatusCode": "200",
"payload":{
"SentItemCount": "65",
"MatchingItemCount": "64",
"CustomerList": [
{
"EntityName": "Franklin LLC",
"EntityID": "06012",
"ContactNum": "913-022-8187"
},
{
"EntityName": "Stanley Firm LLC",
"EntityID": "02398",
"ContactNum": "832-980-2056"
},
{
"EntityName": "Zneith Systems LLC",
"EntityID": "05801",
"ContactNum": "482-120-9406"
}
]
}
}
I don't know what kind of gridview you are using but you can get data from json by 2 ways
using Newtonsoft.Json;
var jsonParsed=JObject.Parse(json);
DataTable dataTable=jsonParsed["payload"]["CustomerList"].ToObject<DataTable>();
// or
List<Customer> customerList=jsonParsed["payload"]["CustomerList"].ToObject<List<Customer>>();
Now you can use or dataTable or customer list as a source to your gridview
if you decided to use a list , you will need to create this class
public class Customer
{
public string EntityName { get; set; }
public string EntityID { get; set; }
public string ContactNum { get; set; }
}

How to extract only part of the JSON and de-serialize it in .netcore

I have .net core application , where an API is called through HTTPClient.
The response for that API in JSON format is as follows:
{
"ID": 25,
"Customer": "CustomerName",
"total": 100,
"details": [
{
"ItemId": "Item1",
"ItemName": "Name1",
"Price": "10"
},
{
"ItemId": "Item2",
"ItemName": "Name2",
"Price": "50"
},
{
"ItemId": "Item3",
"ItemName": "Name3",
"Price": "40"
}
]
}
I get this response from -- > var response = client.GetAsync(ApiPath).Result;
Now from the response variable I need details only for details like :
{
{
"ItemId": "Item1",
"Price": "10"
},
{
"ItemId": "Item2",
"Price": "50"
},
{
"ItemId": "Item3",
"Price": "40"
}
}
I have a DTO class like this :
public class ItemDetails
{
public string ItemId { get; set; }
public string Price { get; set; }
}
Can anyone help in extracting the details according to the DTO class from the main variable "response".
Many thanks!
Try this if you are using newtonsoft
var token = JObject.Parse(response);//load
var detailsToken = token.SelectToken("details");//select
var itemDetails = detailsToken.ToObject<ItemDetails[]>(); //cast to array
Only the properties that exist on ItemDetails will be mapped
You can deserialize the response into an object and take whatever you like from it.
Use the built-in JSON library in .net-core as following
using System.Text.Json;
using System.Text.Json.Serialization;
then make a Response classes to contain the Response values
public class ResponseObject
{
public int ID { get; set; }
public string Customer { get; set; }
[JsonPropertyName("total")]
public int Total { get; set; }
[JsonPropertyName("details")]
public ItemDetails[] Details { get; set; }
}
public class ItemDetails
{
public string ItemId { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
}
finally, deserialize and extract whatever you like as following
var o = JsonSerializer.Deserialize<ResponseObject>(response);
ItemDetails[] itemDetails= o.Details;

Xamarin Refit - Newtonsoft.Json.JsonSerializationException

I have some problems with JSON Serialization.
When I try to deserialize my JSON Object, it returns me this error :
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My problem here is that I have to deserialize my object in two different ways : In a JSON array(e.g.[1,2,3]) to extract "_id", "user" and "name", and then in a JSON array(e.g.["name":"value"]) to extract "books". And I don't know how to do it. Or more precisely, I don't know if it's posible with Refit.
Here is my JSON :
[
{
"_id": "5c014a1e43b6804ed7b642b2",
"__v": 0,
"user": "5c014a1d43b6804ed7b642b1",
"name": "Favoris",
"books": [
{
"_id": "5a8f12e16a16fa06d1f5b0cb",
"title": "Harry Potter et la Chambre des Secrets",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101049,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test1"
}
},
{
"_id": "5a8f12e16a16fa06d1f5b0d0",
"title": "Harry Potter et la Coupe de Feu",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101063,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test2"
}
}
]
}
]
Here is my code :
public async void ViewLibrary()
{
IProjectApi response = ProjectRepository.Instance.ProjectApi;
List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");
this.LibraryItems = library;
}
And my object LibraryModel :
public class LibraryModel
{
public string _id { get; set; }
public string user { get; set; }
public string name { get; set; }
public BookModel books { get; set; }
}
And my method GetLibrary :
[Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Project.Models.BookModel' because the type requires a JSON object
(e.g. {"name":"value"})
In json result your BookModel returning multiple records, so it should be defined as List<BookModel>.
In LibraryModel try using public List<BookModel> books { get; set; }.
Implement these classes anywhere in your code and try to deserialize your json with these classes.
public class Author
{
public string _id { get; set; }
public string name { get; set; }
public int __v { get; set; }
}
public class Content
{
public string brief { get; set; }
}
public class Book
{
public string _id { get; set; }
public string title { get; set; }
public Author author { get; set; }
public string literaryGenre { get; set; }
public object isbn { get; set; }
public string externalImage { get; set; }
public int __v { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int __v { get; set; }
public string user { get; set; }
public string name { get; set; }
public List<Book> books { get; set; }
}

How to create Models in ASP.Net for multi level Json format?

Problem Specification: Build a web api in asp.net to post multi level json formatted data.
Json Format:
{
"InfoList:"[
{
"Name": " Sample String 1",
"URL": " Sample String2",
"Info":[
{
"ZIP": " Sample String3 "
"status": "Sample String4"
}
]
}
]
}
I tried to solve this problem. My models are given bellow:
My Models:
public class Information : InfoList
{
public InfoList InfoList { get; set; }
}
public class InfoList
{
public string Name { get; set; }
public string URL { get; set; }
public Info info { get; set; }
}
public class Info
{
public string ZIP{ get; set; }
public string status { get; set; }
}
Those models Generates this kind of Json Format:
{
"InfoList": {
"Name": "sample string 1",
"URL": "sample string 2",
"Info": {
"ZIP": "sample string 1",
"status": "sample string 2"
}
},
"Name": "sample string 1",
"URL": "sample string 2",
"Info": {
"ZIP": "sample string 1",
"status": "sample string 2"
}
}
I need those parentheses exactly like the problem specification.What to do? I am working with ASP.Net Web API controller.
You're inheriting Information from InfoList so naturally it will get the fields Name, URL etc. Remove the inheritance and change the InfoList and Info members into arrays or lists and you get what you want.
public class Information
{
public InfoList[] InfoList { get; set; }
}
public class InfoList
{
public string Name { get; set; }
public string URL { get; set; }
public Info[] info { get; set; }
}
public class Info
{
public string ZIP{ get; set; }
public string status { get; set; }
}
You just copy your JSON then create C# Class file. Then click Edit -> Paste Special -> Paste JSON as Classes. Thats it...
You need Visual Studio for this.
For more information please see below link
How to show the "paste Json class" in visual studio 2012 when clicking on Paste Special?
Valid JSON
{
"InfoList": {
"Name": " Sample String 1",
"URL": " Sample String2",
"Info": [
{
"ZIP": " Sample String3 ",
"status": "Sample String4"
}
]
}
}
So your class must be like this.
public class Rootobject
{
public Infolist InfoList { get; set; }
}
public class Infolist
{
public string Name { get; set; }
public string URL { get; set; }
public Info[] Info { get; set; }
}
public class Info
{
public string ZIP { get; set; }
public string status { get; set; }
}
You can use http://json2csharp.com/ online tool to create c# class from json data string. Just copy your json and get classes.

How to parse the Json data in WP8?

I'm newbie to windows phone 8 development. I am working on application in which I need parse the Json. please help me with this json data
{
"School": [
{
"info": {
"name": "Dary",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
},
{
"info": {
"name": "Henry",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
}
]
}
this is class
public class Info
{
public string name { get; set; }
public string description { get; set; }
public string startAt { get; set; }
public string endAt { get; set; }
public string status { get; set; }
public int type { get; set; }
}
public class Gui
{
public int size { get; set; }
public string sizeMB { get; set; }
}
public class School
{
public Info info { get; set; }
public Gui gui { get; set; }
}
public class RootObject
{
public List<School> School { get; set; }
}
Thanks in advance.
As Peter Torr suggests, JSON.NET is a great option. There is a DataContractJsonSerializer for serialization in the .net framework, but its not very robust. You can easily add JSON.NET to your project with Nuget. Place your json in a string variable
string json = "<<your json string>>"
or read from a file
string json = File.ReadAllText("<<path to file>>");
Then, the following code will deserialize your text.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
You can lose the root object (it looks like it came from a javascript to C# converter) if you keep only the json array (the text between the brackets [] ), and then you can deserialize just the array.
List<School> school = JsonConvert.DeserializeObject<List<School>>(json);