I just started dabbling with C#, and I've been banging my head over JSON deserialization for a while now. I'm using Newtonsoft.Json library. I'm expecting just a json response of an array of dictionaries as such
[{"id":"669","content":" testing","comments":"","ups":"0","downs":"0"}, {"id":"482","content":" test2","comments":"","ups":"0","downs":"0"}]
Right now I have: (note: download is just a string holding the json string)
string[] arr = JsonConvert.DeserializeObject<string[]>(download);
I've tried many different ways of doing this, each failed. Is there a standard way for parsing json of this type?
You have an array of objects not strings. Create a class that maps the properties and deserialize into that,
public class MyClass {
public string id { get; set; }
public string content { get; set; }
public string ups { get; set; }
public string downs { get; set; }
}
MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(download);
There are only a few basic types in JSON, but it is helpful to learn and recognize them. Objects, Arrays, strings, etc. http://www.json.org/ and http://www.w3schools.com/json/default.asp are good resources to get started. For example a string array in JSON would look like,
["One", "Two", "Three"]
I implement this and hope this is helpful all.
var jsonResponse =
[{"Id":2,"Name":"Watch"},{"Id":3,"Name":"TV"},{"Id":4,"Name":""}]
var items = JsonConvert.DeserializeObject<List<MyClass>>(jsonResponse);
where MyClass is the entity
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Related
The objective is to deserialize a JSON response to a wrapper response class containing a dynamic part, using the new System.Text.Json library from NET Core 3.
That is
{
"fixedProperty": "Hello",
"dynamicProperty": {
"attributeOne": "One",
"attributeTwo": "Two",
}
}
to
public class MyResponseClass
{
public string FixedProperty { get; set; }
public dynamic DynamicProperty { get; set; }
}
// Where the dynamic property is one of the classes.
// (MyDataClassOne in the particular JSON example above)
public class MyDataClassOne
{
public string AttributeOne { get; set; }
public string AttributeTwo { get; set; }
}
public class MyDataClassTwo
{
public string AttributeThree { get; set; }
public string AttributeFour { get; set; }
}
...
The type of the dynamic property in the response is always known in advance (depends on the request), and is one of, say, three different classes.
Could not figure out a clean way to do so, except for not having one wrapper class with a dynamic property but multiple distinct response classes for each of the cases (which obviously works fine but is not the desired solution).
EDIT:
The solution was to use a generic.
How about something like this?
var myResponseClass = new MyResponseClass();
dynamic myClass = JsonSerializer.Deserialize<ExpandoObject>("{\"fixedProperty\":\"Hello\",\"dynamicProperty\": {\"attributeOne\":\"One\",\"attributeTwo\":\"Two\"}}");
dynamic myProperty = JsonSerializer.Deserialize<ExpandoObject>(myClass.dynamicProperty.ToString());
myResponseClass.FixedProperty = myClass.fixedProperty.ToString();
myResponseClass.DynamicProperty = myProperty;
Since the type of the dynamic property in the response is always known in advance (depends on the request), you can use a generic root object:
public class MyResponseClass<T>
{
public string FixedProperty { get; set; }
public T DynamicProperty { get; set; }
}
And then declare T to be whatever known concrete class is required, e.g.
var root = JsonSerializer.Deserialize<MyResponseClass<MyDataClassOne>>(responseString);
var fixedProperty = root.fixedProperty;
var attributeOne = root.DynamicProperty?.AttributeOne;
This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Create a strongly typed c# object from json object with ID as the name
(1 answer)
How can I deserialize JSON with C#?
(19 answers)
Closed 4 years ago.
I'm fairly new to json, and I'm trying to convert some json content to a C# class to store it for later use. I'm having a problem trying to create a class which is suitable for the data structure. An example of the json content is shown below.
Json Data
{
"FirstItem": {
"id": 1,
"type": "foo",
"colours": ["blue", "black", "green"],
"reviews": {
"positive": ["The best", "unbelievable", "Awesome"],
"negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
"neutral": ["OK", "Meh"]
}
},
"SecondItem": {
"id": 2,
"type": "bar",
"colours": ["red", "white", "yellow"],
"reviews": {
"positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
"negative": ["Terrible", "Shocking", "abysmal"],
"neutral": ["OK", "Standard", "Vanilla"]
}
}
}
Edit:
It's worth noting that this is just a small sample of the json data, and I expect to be working with a much larger data set which is always in this format, however the FirstItem, SecondItem (names?) will always be different. I could potentially end up with a MillionthItem.
C# Class
I have created a class based on my limited understanding of the json data above. I think this is where the problem lies - I dont think this class is suitable based on the json above. Here's what I have.
public class Data
{
public string name {get; set;}
public int id {get; set;}
public string type {get; set;}
public string[] colours {get; set;}
public Reviews reviews {get; set;}
}
public class Reviews
{
public string[] positive {get; set;}
public string[] negative {get; set;}
public string[] neutral {get; set;}
}
Converting json to class
To try and convert this, I am using JsonConvert to deserialize the data to a List of a class which I have created. For example:
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var result = JsonConvert.DeserializeObject<List<Data>>(response.Content);
Exception
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[namespace.class]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Summary
I'd appreciate some advice on understanding the json format above, and how I can successfuly convert this
Solution
dbc suggested storing this information in a dictionary, which was exactly what I was needing to do - this allows me to capture the name (FirstItem, SecondItem etc.) as the key and the rest of the class Data as the value.
var result = JsonConvert.DeserializeObject<Dictionary<string, Data>>(response.Content);
Just copy your json and do Edit->Paste Special->Paste Json As Classes in Visual Studio - it will create you the matching class structure.
public class Rootobject
{
public Firstitem FirstItem { get; set; }
public Seconditem SecondItem { get; set; }
}
public class Firstitem
{
public int id { get; set; }
public string type { get; set; }
public string[] colours { get; set; }
public Reviews reviews { get; set; }
}
public class Reviews
{
public string[] positive { get; set; }
public string[] negative { get; set; }
public string[] neutral { get; set; }
}
public class Seconditem
{
public int id { get; set; }
public string type { get; set; }
public string[] colours { get; set; }
public Reviews1 reviews { get; set; }
}
public class Reviews1
{
public string[] positive { get; set; }
public string[] negative { get; set; }
public string[] neutral { get; set; }
}
Then usage will be like:
var rootObject = JsonConvert.DeserializeObject<Rootobject>(jsonString);
I'm trying to convert a string into a list of objects in C#. I've written the following:
My input string is something of the following:
[{"channelID":"15","thresh":"30"},{"channelID":"28","thresh":"14"}]
I'm doing the convering using json.net
var deserializedResultList = JsonConvert.DeserializeObject<TriggerDataList>(result);
Now this is where I start to get hazy. I attempted the following class properties to no avail.
class TriggerDataList
{
[JsonProperty("Triggers")]
public List<TriggerData> Triggers { get; set; }
}
class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
Is it possible to bind that result to a List of TriggerData objects?
Since I tried your code on a clean solution, I will post exactly what I did as an answer rather than comment:
string json = "[{ \"channelID\":\"15\",\"thresh\":\"30\"},{ \"channelID\":\"28\",\"thresh\":\"14\"}]";
List<TriggerData> deserializedResultList = JsonConvert.DeserializeObject<List<TriggerData>>(json);
And the class (remember to make it public):
public class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
The above json (escaped for C#) worked and gave me 2 TriggerData objects in a list.
I am trying to deserialise a json object. The Problem is that the the object also contains subarrays
http://i.imgur.com/WWwEVLR.png
Except for the subarrays everything is working.
I am using Newtonsoft.Json;
Here is my class
public string date_updated { get; set; }
public string date_expires { get; set; }
This is working fine.
For the subarray I did it that way:
public JsonArray contacts { get; set; }
This is my method to deserialise it:
var json = await webClient.GetAsync(new Uri(uri));
var result = await json.Content.ReadAsStringAsync();
Model = JsonConvert.DeserializeObject<Model>(result);
The Array is created well with all fields needed, but the values are not working.
The values are just: Windows.Json.JsonObject as on the picture below.
http://i.imgur.com/Q8bpCoD.png
Why is he not writing the values? How can I get them?
Thank you for your help.
The values are working fine. Using JsonArray tells the deserializer to convert the JSON data to something that is compatible with the type JsonArray. This type is simply a 1:1 representation of the JSON string underneath and is not deserialized into useful data automatically for you.
Also, JsonArray is not even part of the Json.Net library. As the debugger is telling you, it is part of the Windows.Data.Json namespace which is in a different library. You could still access the data directly from each JsonObjects using the various Get methods inside the class ( http://msdn.microsoft.com/en-us/library/windows.data.json.jsonobject.aspx ) but this is probably not the way you want to go.
In your case, you should create a class that represents the data you have inside each of those arrays. If not all entries in the array contains all of the properties of your class, don't worry. Json.Net will simply leave their value empty when deserializing. This will look like:
public class Contact
{
public string type { get; set; }
public string name { get; set; }
public string organization { get; set; }
public string full_address { get; set; }
etc.
}
For good measure, you should also respect the C# naming convention which states that properties should use CamelCase names. To help you with this, you can use the JsonProperty attribute like so:
public class Contact
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("organization")]
public string Organization { get; set; }
[JsonProperty("full_address")]
public string FullAddress { get; set; }
etc.
}
Then, you can replace the type of your contacts property to List<Contact> and the data will be automatically deserialized to a format that you can easily use.
Define new class
class Contact {
public string type { get; set; }
public string name { get; set; }
// etc
}
and modify your ReqInfo_WhoIs_Model class
public string date_updated { get; set; }
public string date_expires { get; set; }
public List<Contact> contacts { get; set; }
I want to create a multidimensional json object based on a c# class. I normally do it like this:
public class foo
{
public string name { get; set; }
public int age { get; set; }
}
And serialize a new instance of the class with a JavaScriptSerializer. But lets say that i want to add another json array containing the persons friends inside the main json array. Example array: Accessing data in a multidimensional JSON array with jQuery
Hope you get the idea. Thanks
If I get your question corect, something like this should work...
public class Person
{
public string name { get; set; }
public int age { get; set; }
public List<Person> Friends { get; set; }
}
How are you creating the JSON version of your class, foo?
JavaScriptSerializer and Controller.JSON (in MVC) support serializing IEnumerable derived types, so you could have the class:
public class foo
{
public string name { get; set; }
public int age { get; set; }
public List<Bar> friends {get; set;}
}
and your JSON serialized class would include the list of Bar objects.