How do I turn a C# object into a JSON string in .NET?
Since we all love one-liners
... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
Documentation: Serializing and Deserializing JSON
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);
}
}
Use Json.Net library, you can download it from Nuget Packet Manager.
Serializing to Json String:
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Deserializing to Object:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );