Tuesday, July 31, 2018

How do I turn a C# object into a JSON string in .NET?



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);
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...