C# – How to 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:


(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?

Best Solution

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