Deserialize JSON to anonymous object
JSON.Net is a powerful library to work with JSON in .Net
There's a method DeserializeAnonymousType you can tap in to.
Update: Json.Net is now included with ASP.Net, however my latest favorite that I use is JsonFX. It's got great linq support as well, check it out.
Update 2: I've moved on from JsonFX, and currently use ServiceStack.Text, it's fast!
how about dynamics, the fastest way I see is this:
dynamic myObject = JsonConvert.DeserializeObject<dynamic>(output);
decimal Amount = Convert.ToDecimal(myObject.Amount);
string Message = myObject.Message;
Note: You will need Newtonsoft.json.dll reference
This can also be done using the in-built JavaScriptSerializer, as follows:
object result = new JavaScriptSerializer().DeserializeObject(JSONData);
This will return an object[] instance, with Key-Value pairs.
How about using the DeserializeObject method, it does not require a specific type. This also solved a similar SO question. The method deserializes to a Dictionary<string, object>
containing name/value pairs.
Update: to clarify the error you get when doing this:
var obj2 = serializer.Deserialize(output, obj.GetType());
Given the type of obj
, Deserialize
will try to create a new instance of the type using a default constructor. Anonymous types in C# does not have a public parameterless constructor, and thus the operation fails.