Creating JSON on the fly with JObject

c#, json, json.net

Solution

Well, how about:

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

Problem

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"; ```

Original source