Quick JSON Serialization/Deserialization in C#

*This outdated*. You should use FridayThe13th the best JSON parser for Silverlight and .NET 4.0.
You don’t need to download an additional libraryto 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: 1 { 2      "some_number" : 108.541, 3      "date_time" : "2011-04-13T15:34:09Z" , 4      "serial_number" : "SN1234" 5 }
You can deserialize the previous JSON into a dictionary like so: 1 using System.Web.Script.Serialization; 2
  3 var jss = new JavaScriptSerializer(); 4 var dict = jss.Deserializestring , string >>(jsonText); 5
  6 Console.WriteLine(dict[ "some_number" ]); //outputs 108.541
So what if your JSON is a bit more complex? 1 { 2      "some_number" : 108.541, 3      "date_time" : "2011-04-13T15:34:09Z" , 4      "serial_number" : "SN1234" 5      "more_data" : { 6          "field1" : 1.0 7          "field2" : "hello"    8      } 9 }
Deserialize like so… 1 using System.Web.Script.Serialization; 2
  3 var jss = new JavaScriptSerializer(); 4 var dict = jss.Deserializestring ,dynamic>>(jsonText); 5
  6 Console.WriteLine(dict[ "some_number" ]); //outputs 108.541 7 Console.WriteLine(dict[ "more_data" ][ "field2" ]); //outputs hello
The field “more_data” gets deserialized into a Dictionary.
You can actually just just deserialize like so: 1 using System.Web.Script.Serialization; 2
  3 var jss = new JavaScriptSerializer(); 4 var dict = jss.Deserialize(jsonText); 5
  6 Console.WriteLine(dict[ "some_number" ]); //outputs 108.541 7 Console.WriteLine(dict[ "more_data" ][ "field2" ]); //outputs hello
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; 2
  3 var jss = new JavaScriptSerializer(); 4 var dict = jss.Deserialize(jsonText); 5
  6 var json = jss.Serialize(dict); 7 Console.WriteLine(json);
Outputs… 1 { 2      "some_number" : 108.541, 3      "date_time" : "2011-04-13T15:34:09Z" , 4      "serial_number" : "SN1234" 5      "more_data" : { 6          "field1" : 1.0 7          "field2" : "hello"    8      } 9 }

좋은 웹페이지 즐겨찾기