Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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": [
      1,
      2,
      3,
      4
    ]
  }
}

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.

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}