需要帮助使用C#javascriptserializer反序列化json字符串

时间:2017-02-16 18:54:45

标签: c# json javascriptserializer

我试图在C#中反序列化以下json字符串,但它无法正常工作。

以下代码返回0的计数。我不确定我做错了什么。

JavaScriptSerializer ser = new JavaScriptSerializer();
Addresses addresses = ser.Deserialize<Addresses>(json);

我的JSON是:

{
  "addresses":[
{
  "first_name":"Sarah",
  "last_name":"Halawani",
  "line1":"1653 OCEAN PKWY",
  "company":"",
  "city":"BROOKLYN",
  "state":"NY",
  "subscriber_id":null,
  "country_name":"United States",
  "country_abbreviation":"USA",
  "latitude":"40.6085",
  "longitude":"-73.9675",
  "verified":true
},
{
  "first_name":"Jean",
  "last_name":"Mizrahi",
  "line1":"1733 OCEAN PKWY",
  "company":"",
  "city":"BROOKLYN",
  "state":"NY",
  "subscriber_id":null,
  "country_name":"United States",
  "country_abbreviation":"USA",
  "latitude":"40.6065",
  "longitude":"-73.9671",
  "verified":true
}
  ]
}

我的课程是:

public class Addresses
{
    public List<Address> address { get; set; }
    public Addresses() { address = new List<Address>(); }
}

public class Address
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string line1 { get; set; }
    public string company { get; set; }
}

1 个答案:

答案 0 :(得分:1)

你错过了财产address。它应该是addresses以匹配JSON属性名称:

public class Addresses
{
    public List<Address> addresses { get; set; }
    public Addresses() { addresses = new List<Address>(); }
}

为避免此类错误,请考虑在Visual Studio中使用代码生成工具,例如http://json2csharp.com/Paste JSON as Classes,然后手动删除不需要的属性。