Using JArray for serializing data from database in WebAPI (C#)

I want to achieve the following JSON data:

[
  {
    "name":"Deutschland",
    "code":"de"
  },
  {
    "name":"Frankreich",
    "code":"fr"
  },
  {
    "name":"Japan",
    "code":"jpn"
  }
]

Currently I’m getting this result of JSON data:

{
    "groups":[
        {
            "name":"Deutschland",
            "code":"de"
        },
        {
            "name":"Frankreich",
            "code":"fr"
        },
        {
            "name":"Japan",
            "code":"jpn"
        }
    ]
}

Here is the code of the Controller:

public dynamic GetGroups()
{
  JObject o = JObject.FromObject(new
  {
     groups = from g in db.QR_Groups
              select new
              {
                name = g.name,
                code = g.code
              }
  });

  return o;

  /*Here I've tried to get JSON data as array without the Property "groups"*/
  //JArray a = new JArray(
  //            from g in db.QR_Groups
  //            select new JValue(g));

  //return a;
}

Can anyone tell me how to retrieve the JSON data as per the first JSON example above?

And is the type “dynamic” good practice for the method?


Source: json

Leave a Reply