使用JArray在WebAPI(C#)中序列化数据库中的数据

时间:2015-06-30 08:27:02

标签: c# json serialization asp.net-web-api json.net

我想实现以下JSON数据:

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

目前我获得了JSON数据的结果:

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

以下是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;
}

有人能告诉我如何根据上面的第一个JSON示例检索JSON数据吗?

类型"动态"该方法的良好实践?

2 个答案:

答案 0 :(得分:3)

试试这个:

var json = JsonConvert.SerializeObject(from g in db.QR_Groups
            select new
            {
                name = g.name,
                code = g.code
            });
  

类型"动态"该方法的良好实践?

不,这不是最好的做法。更好的是创建新类

答案 1 :(得分:3)

首先,不需要手动进行序列化。 ASP.Net WebApi MediaFormatters将根据Request Content-Type处理它。所以创建一个类,如下所示。

public class Group
{        
    public string name { get; set; }
    public string code { get; set; }
}

然后您的Web API端点应为 -

[HttpGet]
public HttpResponseMessage GetCountries()
{
    List<Group> groups = (from g in db.QR_Groups
                               select new Group
                               {
                                   name = g.name,
                                   code = g.code
                               }).ToList();

    return Request.CreateResponse(HttpStatusCode.OK, groups);
}

当我提出Fiddler请求时,我能够获得您感兴趣的输出 -

enter image description here