Archive

Archive for June, 2011

Simple json deserialization in C#

06/06/2011 Leave a comment

In This post a brieflyguid to how to deserialize Json encoded strings. Json is string that can be used t describe complex datastruces fx. C# class’.

A simple Json string could look something like this.


{"TokenId":"tokenid", "TokenSecret":"secretcode"}

This corresponding C# class would look something like this


public class Token
{
public string TokenId { get; set; }
public string TokenSecret { get; set; }
}

     Now given the exaample Json string above we can deserialize using .Net stand javascript deserialze, like this. The Javascriptserializer is placed in System.web.Serializationn.  

   JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Token deserializedToken = javaScriptSerializer.Deserialize<Token>("{\"TokenId\":\"tokenid\", \"TokenSecret\":\"secretcode\"}");

The "deserializedToken" object have now been intialized and both properties "TokenId" and "TokenSecret" has been set to the value folloing the ":" int json string. you can also have more complex structure represented by using in the Json string "[]" you will then have etend your class to contain a list as the example below


public class Token
{
public string TokenId { get; set; }
public string TokenSecret { get; set; }
public IEnumerable<Token> ChildTokens { get; set; }
}

So given the Json string


"{\"TokenId\":\"tokenid\", \"TokenSecret\":\"secretcode\" ,\"ChildTokens\" : [{\"TokenId\":\"tokenid\", \"TokenSecret\":\"secretcode\"}]}"

Your deserialized token object will contain a list with one  ChildToken.

Serialization is left for another post.

I will use this Json deserialization in a feature blogpost  to communicate with a OAuth server.

Categories: C#, Javascript Tags: ,