You don’t need to download an
additional library to serialize/deserialize your objects to/from JSON. Since .NET 3.5, .NET can do it natively.
Add a reference to your project to “System.Web.Extensions.dll”
Let’s look at this example JSON string:
2 | "some_number" : 108.541, |
3 | "date_time" : "2011-04-13T15:34:09Z" , |
4 | "serial_number" : "SN1234" |
You can deserialize the previous JSON into a dictionary like so:
1 | using System.Web.Script.Serialization; |
3 | var jss = new JavaScriptSerializer(); |
4 | var dict = jss.Deserialize<Dictionary< string , string >>(jsonText); |
6 | Console.WriteLine(dict[ "some_number" ]); |
So what if your JSON is a bit more complex?
2 | "some_number" : 108.541, |
3 | "date_time" : "2011-04-13T15:34:09Z" , |
4 | "serial_number" : "SN1234" |
Deserialize like so…
1 | using System.Web.Script.Serialization; |
3 | var jss = new JavaScriptSerializer(); |
4 | var dict = jss.Deserialize<Dictionary< string ,dynamic>>(jsonText); |
6 | Console.WriteLine(dict[ "some_number" ]); |
7 | Console.WriteLine(dict[ "more_data" ][ "field2" ]); |
The field “more_data” gets deserialized into a Dictionary<string, object>.
You can actually just just deserialize like so:
1 | using System.Web.Script.Serialization; |
3 | var jss = new JavaScriptSerializer(); |
4 | var dict = jss.Deserialize<dynamic>(jsonText); |
6 | Console.WriteLine(dict[ "some_number" ]); |
7 | Console.WriteLine(dict[ "more_data" ][ "field2" ]); |
And everything still works the same. The only caveat is that you lose intellisense by using the “dynamic” data type.
Serialization is just as easy:
1 | using System.Web.Script.Serialization; |
3 | var jss = new JavaScriptSerializer(); |
4 | var dict = jss.Deserialize<dynamic>(jsonText); |
6 | var json = jss.Serialize(dict); |
7 | Console.WriteLine(json); |
Outputs…
2 | "some_number" : 108.541, |
3 | "date_time" : "2011-04-13T15:34:09Z" , |
4 | "serial_number" : "SN1234" |
No comments:
Post a Comment