Create Json like this with JObject.FromObject()

Apr 19, 2010 at 12:51 AM


first of all thanks James for creating this tool.

I want to create the following output with the JObject.FromObject() method but it cant figure out to make it happen.

var countries = [{ "value": 1, "name": "Afghanistan" }, { "value": 70, "name": "Aland" }, { "value": 2, "name": "Albania"}];

If i do the following (example)

JObject obj = JObject.FromObject(new { countries = 
              from country in countries
              select new
                  value = country.Id,
                  name = country.DisplayName

It will make json like this:

{ "countries": [ { "value": 1, "name": "Afghanistan" }, { "value": 70, "name": "Aland" }, { "value": 2, "name": "Albania" } ] }

Putting the var countries in front is of course easy and not a problem, but it want it to serialize into an array from the start and not "property: [array]".
I use this to create static .js files that is used for caching data used on my website. In this case a very long list of countries and their id.

Hope someone can help.

Martin :)

Apr 19, 2010 at 1:54 AM

Use JArray.FromObject and append "var countries = " to the front of the JSON.

Apr 19, 2010 at 2:34 AM
Edited Apr 19, 2010 at 2:40 AM



Of course, dont know why i was thinking that only the JObject have the FromOjbect() method.
Even had it working by using the JArray / JObject / JProperty objects instead of an anonymous object.

Better go to bed (4.30 am) :)