反序列化JSON时出现C#错误

时间:2017-04-01 17:04:33

标签: c# arrays json.net

我正在使用json.net在WebApi服务中反序列化传入的json。

var lines = JsonConvert.DeserializeObject<RootObject>(json);

在阅读了许多其他类似的答案之后,仍然会抛出这个错误:

The best overloaded method match for  'Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(string)' has some invalid arguments

输入邮递员用于邮寄的json:

{ "data": [
{"zipcode":"56033","line1":"610 4TH ST","city":"FROST","state":"MN","cid":"1770"},
{"zipcode":"56033","line1":"45375 30TH ST","city":"FROST","state":"MN","cid":"1771"},
{"zipcode":"56033","line1":"115 4TH ST","city":"FROST","state":"MN","cid":"1772"}
]}

poco类是使用:http://json2csharp.com创建的。

  public class Datum
  {
    public string zipcode { get; set; }
    public string line1 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string cid { get; set; }
  }

  public class RootObject
  {
    public List<Datum> data { get; set; }
  }

以下是我在调试api时看到的内容:

{{
  "data": [
    {
      "zipcode": "56032-0056",
      "line1": "208 MAIN BOX 56",
      "city": "FREEBORN",
      "state": "MN",
      "cid": "1732"
    },
    {
      "zipcode": "56033",
      "line1": "610 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1770"
    },
    {
      "zipcode": "56033",
      "line1": "45375 30TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1771"
    },
    {
      "zipcode": "56033",
      "line1": "115 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1772"
    },
    {
      "zipcode": "56033",
      "line1": "E 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1773"
    }
  ]
}}

不确定为什么webapi会添加一组额外的花括号或如何防止它们。

任何人都能看到我错过的东西吗?

1 个答案:

答案 0 :(得分:3)

如果您的json变量是一个字符串,它将起作用。这是一个.NET Fiddle演示。