Over a million developers have joined DZone.

Quickly Create JSON Object from Anonymous Object with Json.NET

DZone's Guide to

Quickly Create JSON Object from Anonymous Object with Json.NET

· ·
Free Resource

Recently I needed to quickly create some temporary JSON objects from some preexisting data. So, I turned to Json.NET, a very popular JSON framework for .NET. Since I got my data on the fly (think parsing some other data structures and you have lots of anonymous results), I didn’t want to create classes for such instances.

Luckily, Json.NET supports serializing anonymous objects. First add the library via NuGet – it is called Newtonsoft.Json. For example:

var obj = new
	user = new
		name = "John",
		age = 21,
		data = new[] { 1, 2, 3, 4 }

var result = JsonConvert.SerializeObject(obj, Formatting.Indented);

If we did that in a console application, we could print out the result. The printout is:

  "user": {
    "name": "John",
    "age": 21,
    "data": [

The code above works on Windows 8, Windows Phone 7 and 8. This way it is dead simple to create JSON representation of your anonymous data. Think REST services.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}