How do I convert a string of json formatted data into an anonymous object?
How do I convert a string of json formatted data into an anonymous object?
using Newtonsoft.Json, use DeserializeAnonymousType:
string json = GetJsonString();
var anonType = new { Order = new Order(), Account = new Account() };
var anonTypeList = new []{ anonType }.ToList(); //Trick if you have a list of anonType
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, anonTypeList);
Based my answer off of this answer: https://stackoverflow.com/a/4980689/1440321
Since nobody mentioned SimpleJSON I'm adding it here. It is a small class (below 50k) and you only need to use one of the files (Unity, .NET or Binary) which is impressive comparing NewtonSoft library (currently JSON.NET). It does not require you to include entire C# compiler in your program and it is relatively fast (needed a few tweaks to make it even faster). It has lazy loading too which will not parse the whole JSON when you only need to read part of it.
Parsing is done like this
JSONNode node = JSON.Parse(str)
And accessing content is like so
node["key"].AsString
node["key"].AsInt
node["key"].AsArray // To access JSON Array
node["key"].AsObject // To access JSON in key as object
...
Or you can just continue using brackets like so
node["key1"]["key2"]["key3"].AsString
To create a JSON string I would use StringBuilder and generate json string manually, which is the fastest method ever. But if you prefer, you can do it using SimpleJson like so
JSONNode node = new JSONObject();
node["key"]= "some data";
node["key1"] = new JSONObject();
node["key1"]["key2"] = "another data";
String s = node.ToString();
Which will generate json string as following
{
"key":"somedata",
"key1": {
"key2":"another data"
}
}
Previous versions wouldn't throw exception if key didn't exist and return default value (as defined in C# standard, but current version will throw exception.