Manipulating JSON using Json.NET


Json.NET makes it convenient to manipulate JSON in C# using dynamic programming. Let’s start with a JSON representation we want to create

{
	"menu": {
		"id": "file",
		"value": "File",
		"popup": {
			"menuitem": [
				{
					"value": "New",
					"onclick": "CreateNewDoc()"
				},
				{
					"value": "Open",
					"onclick": "OpenDoc()"
				},
				{
					"value": "Close",
					"onclick": "CloseDoc()"
				}
			]
		}
	}
}

Here’s how the Json.NET object representation can be created in C# using dynamic programming

dynamic jobj = JObject.FromObject(new 
{
	menu = new
	{
		id = "file",
		value = "File",
		popup = new
		{
			menuitem = new []
			{
				new
				{
					value = "New",
					onclick = "CreateNewDoc()"
				},
				new
				{
					value = "Open",
					onclick = "OpenDoc()"
				},
				new
				{
					value = "Close",
					onclick = "CloseDoc()"
				}
			}
		}
	}
});

To serialize it

var json = JsonConvert.SerializeObject(jobj);
Console.WriteLine(json);

To deserialize JSON string representation to dynamic object

dynamic jobj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jobj.menu.id);

It is fairly easy to extend the object representation and add new items

jobj.foo = new JArray()
{
	new JObject() {
		new JProperty("bar", 10)
	},
	new JObject() {
		new JProperty("bar", 20)
	}
};

That adds a new property to jobj called foo that references a new array containing two objects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s