Json Deserializing to null using Newtosoft Json - c#

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; }
}

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!

Deserialize response from API using custom class 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.

How to deserialize a Json string that has an array of objects but is not using square brackets

I'm trying to deserialize a Json string that has an array with no containing brackets.
{ "id": "983f90j30909j3f",
"moreInfo": {
"info193802": { ... },
"info920938": { ... },
"info849028": { ... }
}
}
This "moreInfo" is an array of items with dynamic keys and does not have square brackets telling that it's an array.
I've tried to deserialize it with Newtonsoft.Json normally ( JsonConvert.DeserializeObject<rootObject>() ) but since this json array isn't really an array it throws an error. Here is my class:
public class RootObject
{
public string Id { get; set; }
public MoreInfo MoreInfo { get; set; }
}
public class MoreInfo
{
public List<Info> InfoList{ get; set; }
}
public class Info
{
properties...
}
How do I go about deserializing this?
Update the root object to use IDictionary<string, Info>
public class RootObject {
public string Id { get; set; }
public IDictionary<string, Info> MoreInfo { get; set; }
}
the dynamic keys will be the key in the dictionary.
Once parsed you access the info via the dictionary's keys
Info info = rootObject.MoreInfo["info193802"];
Newtonsoft can correctly parse the data. The data represents objects, they happen to be nested fairly deep. You can accomplish it a couple of ways, for instance:
dynamic json = JsonConvert.DeserializeObject(response);
var info = json["moreinfo:info913802:example"].Value;
Your other option would be to use Visual Studio, let it create an object you can deserialize to.
Edit
Paste Special
As JSON
Output would be:
public class Rootobject
{
public string id { get; set; }
public Moreinfo moreInfo { get; set; }
}
public class Moreinfo
{
public Info193802 info193802 { get; set; }
public Info920938 info920938 { get; set; }
public Info849028 info849028 { get; set; }
}
public class Info193802
{
public string Example { get; set; }
}
public class Info920938
{
public string Example { get; set; }
}
public class Info849028
{
public string Example { get; set; }
}
The source JSON I used was yours, with one exception:
{ "id": "983f90j30909j3f",
"moreInfo": {
"info193802": { "Example" : "Blah" },
"info920938": { "Example" : "Blah" },
"info849028": {"Example" : "Blah" }
}
}

How to create c# class for below format JSON

Could someone help me in structuring the class for below format JSON.
I have already tried http://json2csharp.com/ tool. It did not work as my list of people are dynamic, i.e. values 123, 124 etc are not pre-defined.
{
"people":
{
"123":"jack henry",
"124":"john henry",
"125":"jill henry",
"215":"jim henry",
...
}
}
public class Root
{
public Dictionary<string, string> people = new Dictionary<string,string>();
}
Using Json.NET:
Root root = new Root();
root.people.Add("123", "jack henry");
//... Add more people
string json = JsonConvert.SerializeObject(root);
Visual Studio > Edit > Paste Special > Paste JSON as classes
public class Rootobject
{
public People people { get; set; }
}
public class People
{
public string _123 { get; set; }
public string _124 { get; set; }
public string _125 { get; set; }
public string _215 { get; set; }
}
You already got an answer for your question. But, looking at the sample JSON looks like you are actually storing a list of persons. If that is the case, you might create classes like this
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class People
{
public List<Person> Persons { get; set; }
//other properties
}
And have your JSON standardized as
{
"Persons": [
{
"Id": 123,
"Name": "Jack"
},
{
"Id": 124,
"Name": "John"
}
]
}
Which will be much more meaningful and readable (by code and human).
Source: http://json2csharp.com/
public class People
{
public string __invalid_name__123 { get; set; }
public string __invalid_name__124 { get; set; }
public string __invalid_name__125 { get; set; }
public string __invalid_name__215 { get; set; }
}
public class RootObject
{
public People people { get; set; }
}

Flattening nested JSON object in JSON.NET

I have a simple JSON like this:
{
"id": 123,
"name": "BaseName",
"variation": { "name": "VariationName" }
}
Is there a simple way to map it with JSON.NET deserialization to:
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string VariationName { get; set; }
}
I can probably do it with a custom converter, but I hoped there would be a simpler way by annotating the class with attributes which would give instructions to deserialize the variation object just using the one property.
You could set up a class for variation and make VariationName a get-only property
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Variation variation { get; set; }
public string VariationName { get { return variation.VariationName; } }
}
class variation
{
public string name { get; set; }
}

Categories

Resources