【问题标题】:Need help deserializing json string with C# javascriptserializer需要帮助使用 C# javascriptserializer 反序列化 json 字符串
【发布时间】:2017-02-17 03:12:32
【问题描述】:

我正在尝试在 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; }
}

【问题讨论】:

  • 你的 json 变量是否包含数据?你没有包含那部分代码
  • 已通过更正拼写错误解决此问题。

标签: c# json javascriptserializer


【解决方案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),然后手动删除不需要的属性。

【讨论】:

  • 感谢 dbc!做到了。
猜你喜欢
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多