Convert a JSON string into a C# object


There could be scenarios in our project wherein we consume a service which returns back a JSON message. These JSON message is infact a stringified version of an object and are recognized as a simple string format by our server side. Decoding them gets difficult at the first shot.

But C# itself has got a solution for this. And that is the JavaScriptSerializer object from the namespace System.Web.Script.Serialization;

Let me take you through the conversion of a JSON string to a custom C# object here. Its pretty simple!!

#1: ADD the following namespace to your code

Using System.Web.Script.Serialization;

#2: INITIALIZE the JavaScriptSerializer object

JavaScriptSerializer jss= new JavaScriptSerializer();

#3: IMPLEMENT the Deserialize method of JavaScriptSerializer, passing two important information – one is the custom object (MyCustomObject) and the JSON string (jsonResponse)

MyCustomObject user = jss.Deserialize<MyCustomObject>(jsonResponse);

#4: DEFINE the MyCustomObject class in your code. Ensure that the object structure matches the JSON string format.

public class MyCustomObject

{

public string myProperty1;

public string myProperty2;

}

You can then use the Deserialized object “user” and get its properties like:
user.Property1 or user.Property2.

For information on the Serialization of C# object to JSON, you can refer my previous post:

Generate JSON String Output in C#

 

Happy Coding!!!

Generate JSON string output in C#


This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.

We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:

using System.Web.Script.Serialization;

The code snippet below show how its done:

//Namespace for the JavascriptSerializer object

using System.Web.Script.Serialization;

public string GenerateJSONString(List<myObject> myCustomList)

{

//Initialize the JavascriptSerializer object   

JavaScriptSerializer serializer = new JavaScriptSerializer();

//Initialize a stringbuilder object to hold the final JSON output     

StringBuilder jsonBuilder = new StringBuilder();

//Generate the JSON string

serializer.Serialize(myCustomList, jsonBuilder);

//Return the JSON string

return Convert.ToString(jsonBuilder);

}

This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.

In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.