Converting a C# Object into JSON String

DZone 's Guide to

Converting a C# Object into JSON String

· Web Dev Zone ·
Free Resource

Some people might think why I am writing so much about basics but the things but in reality  I got lot of questions through email and other communities about very basic things. So I thought instead of replying them into single thread. It is a good idea to write blog post about it and as a result I am writing this blog post.

In this post we are going to learn how we can convert a object into JSON string It is very simple. Let’s first see how we can convert C# Object into JSON string. 

Converting a C# Object into JSON String

So to demo this, I have created a employee class like following.

public class Employee
    public string FirstName { get; set; }
    public string LastName { get; set; }

Now let’s create object of this class and assign some value like following.

Employee employee=new Employee
                    {FirstName = "Jalpesh",
                    LastName = "Vadgama"};

For this demo we are using console application so we have to add System.Web and System.Web.Extensions  reference to access the JavaScript Searilizer class through which we are going to convert this object into JSON string. We are going to add reference like following.


Now with JavaScript Searilizer class which belongs to System.Web.Script.Serializationnamespace we can easily convert C# object into JSON string. Following is a code for that.

var javaScriptSerializer = new
string jsonString = javaScriptSerializer.Serialize(employee);

Now when run this console application. Following is a output as expected.


Here its serialize object into JSON string. Same you can desterilize the JSON string into C# object with Deserialize function.

That’s it. It’s very easy. Hope you like it. Stay tuned for more..

.net & windows, c-sharp, dotnet, html5, json, visual studio, web dev

Published at DZone with permission of Jalpesh Vadgama , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}