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!!!

  1. Tablet popust

    Convert a JSON string into a C# object | The Relentless FrontEnd – Aackose Lal’s Blog

    Reply

Feel free to leave a reply here...

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: