Create a JSON object instead of an array using LINQ / JavaScriptSerializer

Hey guys, hope you all had a good rest during the holidays.

I created a WebService that returns a list of cities and companies in these cities as a JSON string using LINQ / JavaScriptSerializer.

My code is approximately

var data = from c in db.Companies
           group c by c.City into cities
           select new
           {
               city = cities.Key,
               companies = from company in cities
                     select company.Name
           };

JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(data);

This creates the next JSON line

[
  {"city":"Auckland","companies":["Company1","Company2"]},
  {"city":"Wellington","companies":["Company3","Company4","Company5"]}
]

However, I want to make the city key so that I can easily find it

for instance

[
  "Auckland" : {"companies":["Company1","Company2"]},
  "Wellington" : {"companies":["Company3","Company4","Company5"]}
]

Any ideas?

+5
source share
1 answer

Just an idea ... try

var data = db.Companies
             .GroupBy(c => c.City)
             .ToDictionary(g => g.Key,
                           g => new { companies = g.Select(c => c.Name) });

So, this will build Dictionary<string, xxx>where it xxxis an anonymous type with a single property, “companies,” which is a sequence of company names.

+8

All Articles