Deserialize JSON object containing array to C# object - c#

This is my JSON string:
{"type":"motor","ids":["1","2","5","7","8","10"]}
And this is the object I want to generate from it:
public class ElementArray {
public ElementType type;
public String[] ids;
public ElementArray() {
}
}
How can I achieve that? I googled about Json.NET, but they only explain how to deserialize an array but not how to deserialize an object containing an array as a field (see my class above).
What I tried is
JavaScriptSerializer jss = new JavaScriptSerializer();
ElementArray elements = jss.Deserialize<ElementArray>(strJson);
but when I debug the code, the field ids contains null.

IMO simplest way to deal with json is using newtonsoft.json library
http://www.newtonsoft.com/json
And here is example how to deserialize object:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Related

Serialize & Deserialize C# user Defined Classes in .Net

I m working with Core Web API and I have the challenge to nest different class objects into an ArrayList and send them over the FromBody object, the issue is I have to pack them in a way that on the receiving side I deserialize them into their respective objects.
an example is below.
[Serializable]
public class M1
{
public string Name { get; set; }
public int Age { get; set; }
}
[Serializable]
public class M2 : M1
{
public string Gender { get; set; }
public int Height { get; set; }
}
static void Main(string[] args)
{
try
{
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
//Method1
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(alist, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Method 2
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(mObj, Formatting.Indented);
result = result + Newtonsoft.Json.JsonConvert.SerializeObject(m2Obj, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
For the first method its throwing error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SerliazeDeserliaze.M1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array of a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
for the second method, it says
Additional text encountered after finished reading JSON content: {. Path '', line 4, position 2.
By doing some hack I have done that different way.
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
ArrayList alistb = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
string json = JsonConvert.SerializeObject(alist, Formatting.Indented, new KeysJsonConverter(typeof(ArrayList)));
alistb= JsonConvert.DeserializeObject<ArrayList>(json, new KeysJsonConverter(typeof(ArrayList)));
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(alistb[0].ToString());
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(alistb[1].ToString());
Serializing the list into JSON and then Deserializing it in a reverse way get the job done.
If you serialize list of object, you should deserialize it also into list:
string result = Newtonsoft.Json.JsonConvert.SerializeObject(aList, Formatting.Indented);
List<M1> mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<List<M1>>(result);
JSON supports the following two data structures,
Collection of name/value pairs - This Data Structure is supported by different programming languages.
Ordered list of values - It includes an array, list, vector or sequence, etc.
JSON has the following styles,
Object
An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
Array
Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
We can implement JSON Serialization/Deserialization in the following three ways:
Using JavaScriptSerializer class
Using DataContractJsonSerializer class
Using JSON.NET library
Using DataContractJsonSerializer
DataContractJsonSerializer class helps to serialize and deserialize JSON.
It is present in namespace System.Runtime.Serialization.Json which is
available in assembly System.Runtime.Serialization.dll. Using the
class we can serialize an object into JSON data and deserialize JSON
data into an object.
Let's say there is Employee class with properties such as name, address, and property values also assigned. Now we can convert the Employee class instance to the JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
Let's create a custom class BlogSite for serialization and deserialization,
[DataContract]
class BlogSite
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and create an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
BlogSite bsObj = new BlogSite()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
MemoryStream msObj = new MemoryStream();
js.WriteObject(msObj, bsObj);
msObj.Position = 0;
StreamReader sr = new StreamReader(msObj);
// "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}"
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
C# Deserialization
In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an instance of MemoryStream class to write an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from MemorySteam object.
string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
Response.Write("Name: " + bsObj2.Name); // Name: C-sharpcorner
Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge
}
C# Using JavaScriptJsonSerializer
JavaScriptSerializer is a class that helps to serialize and deserialize JSON. It is present in the namespace System.Web.Script.Serialization is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.
Following code, a snippet is to declare a custom class of BlogSites type.
class BlogSites
{
public string Name { get; set; }
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Serializing object to json data
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"}
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
// Deserializing json data to object
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;
// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];
C# Using Json.NET
Json.NET is a third-party library that helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open-source software and free for commercial purposes.
The following are some awesome features,
Flexible JSON serializer for converting between .NET objects and JSON.
LINQ to JSON for manually reading and writing JSON.
High performance, faster than .NET's built-in JSON serializers.
Easy to read JSON.
Convert JSON to and from XML.
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let’s start learning how to install and implement:
In Visual Studio, go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manager Solution and type “JSON.NET” to search it online. Here's the figure,
Json.NET
Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Convert BlogSites object to JOSN string format
string jsonData = JsonConvert.SerializeObject(bsObj);
Response.Write(jsonData);
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
string json = #"{
'Name': 'C-sharpcorner',
'Description': 'Share Knowledge'
}";
BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);
Response.Write(bsObj.Name);
JSON.NET, visit here.
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the

Deserialize raw JSON and convert to custom C# Object

I have the following raw JSON string:
[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]
I have tried the following without luck:
My custom object class:
public class MyObject
{
public string msg { get; set; }
public string id { get; set; }
public string chn { get; set; }
}
JSON string:
string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";
1st attempt at deserilization using System.Web.Script.Serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);
2nd attempt at deserilization using Newtonsoft.Json:
MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);
Both attempts fail. Any suggestions?
You have a JSON array of strings, not an object with property names.
So the best you can do here is to deserialize the array:
IEnumerable<string> strings =
JsonConvert.DeserializeObject<IEnumerable<string>>(str);
...then use the resulting sequence strings as you see fit.
With PubNub, you can just pass in the native String, Dictionary, or Array, and we'll JSON encode it for you on the publish side, and auto JSON decode for you on the subscriber side.
It's because your 'custom object' isn't equivalent to the json representation. The json you're deserializing is just a string[] in C# (you can also use List<string> or other IEums).
So in code you're looking for;
string[] theJson = JsonConvert.DeserializeObject<string[]>(str);
MyObject would be used for the following json;
{
"msg":"Hello World!",
"id":"94952923696694934",
"chn":"MyChannel"
}

json serialize list in list

I get a list with list in json And want to convert the json to matrixList Object but cant get it to work Im getting this error
System.Collections.Generic.Dictionary`2[System.String,System.Object]
here is my code
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
matrixList mxList = (matrixList)json_serializer.DeserializeObject("{ \"matrix\": "[[\"1\",\"email1#gmail.com\"],[\"2\",\"email2#gmail.com\"],[\"3\",\"email3#gmail.com\"],[\"4\",\"email4#gmail.com\"]]" }");
The values of the Json is just an example
public class matrixList
{
public List<List<string>> matrix { get; set; }
}
My question then why wont it work I have searched on the error and only found some with Json syntax error but Im not able to see any error.
Tahks for the help
Try adding a RootObject first.
public class RootObject
{
public RootObject(){}
public List<string> itemList{get;set;}
}
Then try deserializing to the RootObject type.
When deserializing Lists this works with Newtonsoft.JSON serializer.
serializer.DeserializeObject<RootObject>(jsonInput);

Deserializing Json with numbered keys in ServiceStack

I have such Json:
{
data:{
"50":{"id":"50","name":"test", etc...},
"51":{"id":"51","name":"test", etc...},
"53":{"id":"53","name":"test", etc...},
...
}
}
What is the correct way to deserialize this Json?
[UPDATED]
I think I must to adjust my question. Is it possible to parse Json using class with description of objects. E.g. I have such class and Json which I parse with .FromJson():
public class Data
{
public ...
}
public class Category
{
public int Id{get;set;}
public string Name{get;set;}
}
What should be instead three dots?
Your json contains an object O. This object has a member data that is a dictionary from strings or ints to your category objects. So try something like:
class Root
{
public Dictionary<int, Category> data;
}
var o = JavaScriptSerializer.Deserialize<Root>(json);
If you are using servicestack.text just do
var v = myJson.FromJson();
Don't forget that servicestack is best used when serialization also made with servicestack.
the best way to deserialize Json object to c# class in JSON.NET project (found on codeplex)
the deserialize example is:
JsonConvert.DeserializeObject<Category>(jsonString);

Parsing Unknown JSON using JavascriptSerializer in C#

How can I use JavaScriptSerializer to parse some unknown dynamic JSON. In particular, I'm writing my own wrapper for the Google Calendar API. An event has an object called extendedProperties with both a private object and shared object containing an unknown set of properties:
"extendedProperties": {
"private": {
"UnknownKey1": "UnknownValue1",
"UnknownKey2": "UnknownValue2",
"UnknownKey3": "UnknownValue3"
},
"shared": {
"UnknownKey1": "UnknownValue1",
"UnknownKey2": "UnknownValue2",
"UnknownKey3": "UnknownValue3"
}
}
I want to create a class like this for the JavaScriptSerializer:
public class ExtendedProperties
{
public ??? #private { get; set; }
public ??? shared { get; set; }
}
Of course there are problems.
(1) Does the serializer understand the ampersand so it will parse the property 'private'?
(2) What would the return type be for the properties that the JavaScriptSerializer could read/write? Some sort of Dictionary?
Thanks in advance!
var serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<IDictionary<string, object>>(jsonStr);
I have used this code to deserialize unknown json objects.
The parser understands the # symbol. You can use dynamic as your type if you're using .net 4. You could try Dictionary<string,string> although I've always had problems with serializing and deserializing dictionaries to the same reference object. List<KeyValuePair<string, string>> usually does the trick.

Categories