Quantcast
Channel: JavaScript – delog
Viewing all articles
Browse latest Browse all 21

Manipulating JSON using Json.NET

$
0
0

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.


Filed under: .NET, JavaScript

Viewing all articles
Browse latest Browse all 21

Trending Articles