Reputation: 650
What is the most painless way to deserialize this JSON in C# using JSON.NET?
{
"serNo":{
"A4":{
"vol":[["0","100","0,1"],["0","n","0"]],
"fix":"900"
},
"A3":{
"vol":[["0","200","0,5"],["0","n","0"]],
"fix":"700"
}
}
}
To create a separate class or as collection?
EDIT: There will be multiple "serNo" properties.
Upvotes: 1
Views: 1078
Reputation: 650
OK, I solved the problem with JSON.NET by creating this class:
class Counter { public double[][] vol { get; set; } public double fix { get; set; } }
and
deserialized JSON with this expression:
Dictionary<string, Dictionary<string, Counter>> counters = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Counter>>>(arg.Args[7]);
Where arg.Args[7] is JSON.
Upvotes: 1
Reputation: 10231
You can use the build in lightweight JavaScriptSerializer. No attributes are required on the classes you want to serialize/deserialize.
It can also handle anonymous types.
Serialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectAsJsonString = serializer.Serialize(objectToSerialize);
Deserialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SomeClass deserializedObject = serializer.Deserialize<SomeClass>(objectToDeserialize);
Here is the link to an earlier related question/answer: Error converting JSON to .Net object in asp.net
Upvotes: 1
Reputation: 33139
In my opinion, the most painless way to deserialize any JSON is to use the JSON.NET library. See also http://json.codeplex.com.
EDIT: Also see this other question on Stack Overflow: How to deserialize with JSON.NET?
Upvotes: 4