【问题标题】:Deserializing JSON with JSON.NET in Windows 8 Store App在 Windows 8 Store App 中使用 JSON.NET 反序列化 JSON
【发布时间】:2013-02-28 20:46:17
【问题描述】:

我正在尝试将以下 JSON 反序列化为我的 Win 8 应用程序中的一个对象:

{
"success":true,
"pharmacies":[
{
"name":"Test Pharmacy",
"phone":null,
"description":"sample description",
"pharmacyid":"1234567",
"pic":"/1341864197.png",
"address":"211 Warren St., #205",
"city":"Newark",
"state":"NJ",
"zipcode":"07103",
"delivery":true,
"dob_check":false,
"name_check":false,
"can_pickup":true,
"barcode_template":"9999999XX"
}
]
}

这是我正在使用的模型:

public class PharmacyList
{
    public List<Pharmacy> pharmacies { get; set; }
}
public class Pharmacy
{
    public string pharmacyid { get; set; }
    public string name { get; set; }
    public string phone { get; set; }


}

这是我用来反序列化的代码

json = await results.Content.ReadAsStringAsync();
List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json);

我收到以下异常:

:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[PharmacyHC.Models.PharmacyList]',因为该类型需要 JSON 数组(例如 [1,2,3]) 正确反序列化。

我是在尝试反序列化为错误的类型,还是应该在从 API 返回时以不同方式格式化 JSON?

【问题讨论】:

  • 致对这篇文章投了反对票的人:请留下一个不充分的理由。

标签: json microsoft-metro json.net


【解决方案1】:

我刚刚意识到我犯了一个愚蠢的错误。 p 应该被声明为 PharmacyList 类型而不是列表对象,因为 PharmacyList 的类声明已经包含一个 List 对象。

List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json);

应该是的

PharmacyList p = JsonConvert.DeserializeObject<PharmacyList>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多