Example:
Single: { "field1":"value1","field2":"value2" }
Array: [ { "field1":"value1","field2":"value2" }, { "field1":"value1","field2":"value2" } ]
For the single, the .NET Framework has the key, you need to create a class that has public fields or properties matching the field names on your JSON string, example:
public class Test
{
public string field1 { get; set; }
public string field2 { get; set; }
}
And the code to serialize your Single JSON is this:
Test myDeserializedObj = (Test)JavaScriptConvert.DeserializeObject(Request["jsonString"], typeof(Test));
and voilá! you got yourself a strong-typed object with client-side data, sweet!
But and if I want a list of data of the same type, say an Array, how is it done? The .NET Framework hasn't got the answer for this one..
You have to download and reference the following DLL
Once it's done:
List< test > myDeserializedObjList = (List< test >)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List< test >));
and yes! you're done :)
How easy is this? It's perfect for your lightweight ajax applications with .NET backend.
Please post comments!
See you soon
4 comments:
Nice, worked very well!
Note: the API has changed, now it's Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString);
Thanks for the feedback :)
Just updated the post to reflect the API changes, thanks!
Nice and Sweet :D
It's a nice and simple feature :D.
This DLL don't exist for .NET 1.1.
I used this static method [ Dim myDeserializedObj As String = Newtonsoft.Json.JsonConvert.SerializeObject(MyList)
Response.Write(myDeserializedObj)]
And Just Work Fine!
Thanks Bro :D
Post a Comment