Home > C#, Javascript > Simple json deserialization in C#

Simple json deserialization in C#

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: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: