Computer Beacon high quality .NET libraries in open source

To parse a string

To parse a string into a JsonObject or JsonArray, simply pass the string as an argument to the constructor.

string s = "{\"Name\":\"Hello World", X:123}";

JsonObject jo = new JsonObject(s);

To dynamically create a JsonObject or JsonArray

To add objects at runtime, simply call the Add method. JsonArray and JsonObjects can also be nested within each other.

//Add objects directly to index
JsonObject jo1 = new JsonObject();
jo1["Name"] = "Earth";
jo1["Mass"] = 5.9736e24;

//Add objects using the Add() method
JsonObject jo2 = new JsonObject();
jo2.Add("Name", "Mars");
jo2.Add("Mass", 6.4185e23);

JsonArray planets = new JsonArray();
planets.add(jo1);
planets.Add(jo2);

Using anonymous types in constructors (new in version 4.1)

Starting in version 4.1, you can use anonymous types to initialize JsonObject and JsonArray instances:

JsonArray planets = new JsonArray(new object[]{
    new JsonObject(new {
        Name = "Earth",
        Mass = 5.9736e24d
    }),
    new JsonObejct(new {
        Name = "Mars",
        Mass = 6.4185e23d
    })
});

To stringify a JsonObject or JsonArray

The ToString() method converts a JsonObject or JsonArray instance to its string representation

Console.WriteLine(planets.ToString());

To serialize and deserialize a .NET type to JSON

var u = new User();
...

//serialize
string s = Serializer.Serialize(u);

//deserialize
var u2 = Serializer.Deserialize<User>(s);