Creating JSON on the fly with JObject


For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.

I have the following code:

var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");

This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:

jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";

This question is tagged with c# json

~ Asked on 2013-08-15 05:14:15

The Best Answer is


Well, how about:

dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";

~ Answered on 2013-08-15 05:34:37


You can use the JObject.Parse operation and simply supply single quote delimited JSON text.

JObject  o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'

This has the nice benefit of actually being JSON and so it reads as JSON.

Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.

JObject o = JObject.FromObject(new
    channel = new
        title = "James Newton-King",
        link = "",
        description = "James Newton-King's blog.",
        item =
            from p in posts
            orderby p.Title
            select new
                title = p.Title,
                description = p.Description,
                link = p.Link,
                category = p.Categories
}); documentation for serialization

~ Answered on 2015-01-05 18:04:26

Most Viewed Questions: