Hui Hui - 6 months ago 24
JSON Question

Turn C# object into a JSON string in .NET 4

I have classes like these:

class MyDate
{
int year, month, day;
}

class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}


And I would like to turn a
Lad
object into a JSON string like this:

{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}


(without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files. Are there other options besides manually creating a JSON string writer?

Answer

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}