Over a million developers have joined DZone.

Quickly Create JSON Object from Anonymous Object with Json.NET


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 Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}