Quickly Create JSON Object from Anonymous Object with Json.NET
Join the DZone community and get the full member experience.
Join For FreeRecently 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.
Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments