Daily using/supporting

Get Firefox browser!
Get Thunderbird!
Get Opera browser!
Get The Gimp!
Get Inkscape!
Get LibreOffice!
Get Videolan!
Get Linux!
Get Mandriva!
Get Joomla!
Hacker Emblem

Archives

Which topics would you like us to cover more?

Latest comments

Latest tweets

about 2 days ago Using REDIPS.drag to add drag and drop to your .Net webapplication #li #dib0 http://t.co/n8zY3s7d
about 8 days ago http://t.co/cknQcDbo #Kindle
about 16 days ago Freedom isn't the ability to choose what to do or say, but the ability to choose what not to do or say #freedom
12 Apr 2012 Force the use of a networking adapter using C# #li #dib0 http://t.co/ZTJOPzOz
9 Apr 2012 Mandriva 2010.2 and USB devices in Virtualbox http://t.co/fwq9gbHB
9 Apr 2012 Execute a http request to you own site with PHP http://t.co/DIvWPrpd
Home Architecture, security and coding C#, JSON data and serialization
C#, JSON data and serialization
Written by Division by Zero   
Saturday, 27 February 2010 10:44

On a personal project I had to use JSON data in C#. The first quick and dirty way was to interpret it by string manipulation. Of course this is very buggy. That the JSON data contained a lot of complex objects didn't help much. What I wanted was a JSON data serializer. I could write my own, but as a lazy developer someone somewhere would have probably done that for me. After a quick search I found that the framework already had it: the JavaScriptSerializer (in the System.Web.Script.Serialization namespace, add the System.Web.Extensions assembly as a reference).

Now it had to meet my requirements. Because of the large amount of the data and my need for a small subset of it, I didn't want to work out a large class structure. XML serializers demand that the XML elements exist in you model, but did the JavaScriptSerializer demand the same? Luckily it didn't.

Here's an example. If your JSON data is something like {"name": "Division by Zero", "site" : "http://www.dib0.nl"} and you just need the name, do the following:

public class Person
{
public string Name;
}
JavaScriptSerializer scriptSerializer = new JavaScriptSerializer();
Person p = scriptSerializer.Deserialize("{\"name\": \"Division by Zero\", \"site\" : \"http://www.dib0.nl\"}");

It works like a charm. Really easy to use an very handy.

Tags:
 

Add comment


Security code
Refresh

Beware of bugs in the above code; I have only proved it correct, not tried it. - Donald E. Knuth


© 2009 - 2012, Division by Zero

Template based on the empire template by joomlashack 

Valid XHTML 1.0 Strict  Valid CSS!  Creative Commons License
This work by Division by Zero is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.