无法获取jsonresult数据的内容

时间:2016-07-24 18:07:10

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

客户端获取对web api的请求然后得到响应,因为这里的json数据是请求和发布响应客户端数据的web api ..

这是web api方法,经过一些流程后回复客户端;

public ActionResult GetBooks(){
    ...
    return new JsonResult()
        {
            Data = new { draw = draw, recordsFiltered = totalRecords, recordsTotal = totalRecords, data = booklist },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
}

以下是客户端从web api获取响应并将其发布到视图:

HttpResponseMessage response = client.GetAsync("api/Book/GetBooks/").Result;
JsonResult result = null;
if (response.IsSuccessStatusCode)
{
    result = response.Content.ReadAsAsync<JsonResult>().Result;
}
List<Book> booklist = null;

return Json(new { draw = result.Data.draw, recordsFiltered = result.Data.totalRecords, recordsTotal = result.Data.totalRecords, data = result.Data.booklist }, JsonRequestBehavior.AllowGet);

当您看到相同的属性时,我会尝试使用result.Data.propertyName 但是不可能。

我不想在客户端方法中更改返回属性名称。

我该怎么办?

这里的响应(结果。)数据如下:

{{
  "draw": "1",
  "recordsFiltered": 670,
  "recordsTotal": 670,
  "data": [ 
    {
      "Title": "A Popular Survey of the Old Testament",
      "Publisher": "Baker Academic",
      "Description": "Illustrated with photos, charts, and maps, and written in their understanding of Old Testament people and events.",
      "Authors": [
        "Norman L. Geisler"
      ],
      "Id": "579273aa2711d31de88933bd"
    },

    {
      "Title": "A Village on the Moon / Um Povoado Na Lua",
      "Publisher": "Trafford Publishing",
      "Description": "Since the beginning of time, mankind has looked up at the Moon and wondered. Many have seen figures on that light in the sky and universo. Um grupo de aventureiros se propôs a colonizar esse planeta e aqui está a sua história.",
      "Authors": [
        "Charles A. Hindley"
      ],
      "Id": "579273aa2711d31de8893438"
    }
  ]
}}

以正确的json格式,我们可以使用result.Data.drawresult.Data.data[0]获取数据,但在这种情况下我遇到了麻烦..

如何删除多余的范围?

1 个答案:

答案 0 :(得分:1)

使用内部范围,可以为客户端派生以下模型。

public class BookData
{
    public string Title { get; set; }
    public string Publisher { get; set; }
    public string Description { get; set; }
    public string[] Authors { get; set; }
    public string Id { get; set; }
}

public class GetBooksResult
{
    public string draw { get; set; }
    public int recordsFiltered { get; set; }
    public int recordsTotal { get; set; }
    public BookData[] data { get; set; }
}

用那个

HttpResponseMessage response = await client.GetAsync("api/Book/GetBooks/");
GetBooksResult result = null;
if (response.IsSuccessStatusCode)
{
    result = await response.Content.ReadAsAsync<GetBooksResult>();
}
return Json(result, JsonRequestBehavior.AllowGet);

在客户端上,响应是从web api返回的原始json字符串。无需JsonResult。您将在客户端返回到模型中的数据解析并传递给它。