Deserialize response from API using custom class c# - c#

I am receiving the json response of below format from an api. I am trying to deserialze it with custom class.
{
"TraceEvent": {
"Attributes": {
"Commodity": "APPLES",
"Variety": "Green"
},
"Codes": [{
"devicename": "",
"code": "901491877572115",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}, {
"devicename": "",
"code": "6657287134488755",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}
]
}
}
Below is my custom class used for deserialize
public class EventContainer
{
[JsonProperty("TraceEvent")]
public TraceEvent TraceEvent { get; set; }
}
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("codes")]
public TraceCodes Codes { get; set; }
}
public class TraceAttributes
{
[JsonProperty("commodity")]
public string Commodity { get; set; }
[JsonProperty("variety")]
public string Variety { get; set; }
}
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
public class TraceCode
{
[JsonProperty("devicename")]
public string DeviceName { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
}
In the receiver side, i am getting null for the Codes. Plesae refer my debug screen in api receiver code,
Can any one tell me how to rewrite my custom class to deserialize the Codes list from JSON api
Thanks for the help.

Change the class structure. The Codes should be in TraceEvent class not in its own class
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Remove below class
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}

TraceEvent has a property
public TraceCodes Codes { get; set; }
And TraceCodes is another object with a list of codes:
public List<TraceCode> Codes { get; set; }
This would mean there would have to be a structure like this:
{
"TraceEvent": {
"Codes": {
"Codes": [
{ … },
{ … },
}
}
}
}
So the "Codes" part is double. Instead, you need to modify your TraceEvent to have that list directly:
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Btw. that should have actually resulted in a JsonSerializationException, so you should check whether that gets swallowed somewhere.

Related

How to deserialize multidimensional JSON

I know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!

Json.Net deserialize JSON objects

I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object.
Json
{
"success":true,
"data":{
"24486146360":{
"rfid":"123465789456",
"products":[
{
"sale_id":35,
"quantity":2,
"price":"1",
"total":"2",
"unit":"uni",
"sku":14
},
{
"sale_id":36,
"quantity":2,
"price":"2.5",
"total":"5",
"unit":"uni",
"sku":17
}
]
},
"24758345953":{
"rfid":"2129",
"products":[
{
"sale_id":39,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"64577015900":{
"rfid":"1934",
"products":[
{
"sale_id":40,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"56768990934":{
"rfid":"1746",
"products":[
{
"sale_id":46,
"quantity":1,
"price":"8.00",
"total":"8",
"unit":"UN",
"sku":20
}
]
}
}
}
I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following:
My Class create help for json2sharp
public class Consumo
{
public string rfid { get; set; }
public List<ConsumoProduto> products { get; set; }
}
public class ConsumoProduto
{
public int sale_id { get; set; }
public double quantity { get; set; }
public string price { get; set; }
public string total { get; set; }
public string unit { get; set; }
public int sku { get; set; }
}
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public List<Consumo> Registro { get; set; }
}
My Problem
how do I convert Json to a valid object using Json.Net?
Test
I tried to do this and I could not
Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>.
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public Dictionary<string, Consumo> Registro { get; set; }
}
Then, you need to deserialize the JSON into the RetornoConsumo class:
var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);
Fiddle: https://dotnetfiddle.net/vfhdXp

Json Deserializing to null using Newtosoft Json

I have the following json:
{
"cuisines": [
{
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
},
{
"cuisine": {
"cuisine_id": 1,
"cuisine_name": "American"
}
},
{
"cuisine": {
"cuisine_id": 4,
"cuisine_name": "Arabian"
}
},
{
"cuisine": {
"cuisine_id": 151,
"cuisine_name": "Argentine"
}
}
]
}
Im using RestSharp to get the data and sending it to JSON.Net:
JsonConvert.DeserializeObject<Cuisines>(content)
And I'm using the following classes:
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}
What is wierd is, the return data is finding 81 cuisine objects on my request, but all the Cuisine info is null.
You model needs one more class. So it should be
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class CuisineWrapper
{
public Cuisine cuisine { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<CuisineWrapper> AllCuisines { get; set; }
}
Your classes definitions doesn't match provided JSON. Top level array contains objects with a single property (object) cuisine, like so:
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
where as your C# List<Cuisine> contains objects directly exposing cuisine_id and cuisine_name. If you can't change JSON, decorate class Cuisine with JsonObjectAttribute
You actually have 3 objects - A root object that contains a property named cuisines that is a collection of Cuisine.
When you paste your JSON as classes in visual studio you get the following structure (which you would probably want to rename some things and list-ify the array)
public class Rootobject
{
public Cuisine[] cuisines { get; set; }
}
public class Cuisine
{
public Cuisine1 cuisine { get; set; }
}
public class Cuisine1
{
public int cuisine_id { get; set; }
public string cuisine_name { get; set; }
}
Your JSON is nested more than your class structure. If you can change your JSON to the form:
"cuisines": [
{
"cuisine_id": 152,
"cuisine_name": "African"
},
{
"cuisine_id": 1,
"cuisine_name": "American"
},
.. etc
Then it will match your class structure.
Alternatively, change your class structure to match the JSON:
public class Cuisine
{
[JsonProperty("cuisine")]
public CuisineData data { get; set; }
}
public class CuisineData
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}

Parsing Custom JSON Response with JSON.NET

This is my first attempt at trying to parse a json response with json.net and I am totally lost. I have included a section of the parsed json below. What I would like to do do is loop through the backlinks array. I have tried implementing various samples from the newtonsoft documentation, but they don't seem to work and I think it is because my json doesn't match their samples and I don't have knowledge to make the necessary corrections. If someone could provide some C# code to get me started I would really appreciate it.
Thanks,
Chaos
{
"accounts": [
{
"10555": {
"sites": [
{
"12222": {
"pages_indexed_in_bing": {},
"download_time": null,
"backlinks": [
{
"anchor_text": "websites for insurance agents",
"source_url": "http://win-winbusinesses.com/insurance/how-to-building-an-effective-insurance-website/",
"found_on": "2015-07-15",
"page_authority": null,
"link_strength": 3,
"domain": "win-winbusinesses.com",
"domain_authority": 17
},
First of all, as stated before, the JSON you've provided is invalid.
I assume it should look like this:
{
"accounts": [
{
"10555": {
"sites": [
{
"12222": {
"pages_indexed_in_bing": {
},
"download_time": null,
"backlinks": [
{
"anchor_text": "websites for insurance agents",
"source_url": "http://win-winbusinesses.com/insurance/how-to-building-an-effective-insurance-website/",
"found_on": "2015-07-15",
"page_authority": null,
"link_strength": 3,
"domain": "win-winbusinesses.com",
"domain_authority": 17
}
]
}
}
]
}
}
]
}
And according to this JSON, you're classes should look like this if you want newtonsoft to succeed parsing:
public class PagesIndexedInBing
{
}
public class Backlink
{
public string anchor_text { get; set; }
public string source_url { get; set; }
public string found_on { get; set; }
public object page_authority { get; set; }
public int link_strength { get; set; }
public string domain { get; set; }
public int domain_authority { get; set; }
}
public class __invalid_type__12222
{
public PagesIndexedInBing pages_indexed_in_bing { get; set; }
public object download_time { get; set; }
public List<Backlink> backlinks { get; set; }
}
public class Site
{
public __invalid_type__12222 __invalid_name__12222 { get; set; }
}
public class __invalid_type__10555
{
public List<Site> sites { get; set; }
}
public class Account
{
public __invalid_type__10555 __invalid_name__10555 { get; set; }
}
public class RootObject
{
public List<Account> accounts { get; set; }
}
As you can see there might be problems since you using class/var names that are only numerical, so you probably should check this as well.

Parse JSON object in C#

I use JSON.NET and I would like to parse the following object which I get from a WebService. Can someone post an example on how to do that?
#"{""MessageType"":0,
""Message"":""Success"",
""Value"":[
{""listId"":1,
""listName"":""DemoList"",
""itemInList"":[
{
""fromDate"":""\/Date(1228946400000)\/"",
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""water"",
""creationDate"":""\/Date(1339448400000)\/"",
""typeId"":1
},
{
""fromDate"":null,
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""gala"",
""creationDate"":""\/Date(1304370000000)\/"",
""typeId"":1
}
]}
]}"
JSON Object
{
"MessageType":0,
"Message":"UserLists",
"Value":
[
{
"listId":1,
"listName":"DemoList",
"itemInList"
[
{
"fromDate":"\/Date(1228946400000)\/",
"fromLocation":null,
"toLocation":null,
"originalRequest":"water",
"creationDate":"\/Date(1339448400000)\/",
"typeId":1
},
{
"fromDate":null,
"fromLocation":null,
"toLocation":null,
"originalRequest":"gala",
"creationDate":"\/Date(1304370000000)\/",
"typeId":1
}
],
"numberOfItems":2
}
]
}
Thanks.
You need to create some entity like this:
public class Entity
{
public int MessageType { get; set; }
public string Message { get; set; }
public List<EntityValue> Value { get; set; }
}
public class EntityValue
{
public int listId { get; set; }
public string listName { get; set; }
public List<ItemInList> itemInList { get; set; }
}
public class ItemInList
{
public DateTime? fromDate { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
public string originalRequest { get; set; }
public DateTime creationDate { get; set; }
public int typeId { get; set; }
}
The entity must has the same structure like the json data.
And you can call the Method:
JsonConvert.DeserializeObject<Entity>(json);
If it has any exception,you need to adjust the entities until it works.
Please read the below link for parsi in metro style application.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh770287.aspx

Categories

Resources