我有API端点,该端点返回我的JSON对象
在这里
{
"results": [
{
"id": 182,
"title": "1-Day Private Beijing Tour to Tian'anmen Square, Forbidden City and Badaling Great Wall",
"price": "162",
"duration": "8",
"duration_type": "1",
"cover_image": {
"id": 308,
"img_path": "upload/images",
"img_file": "6d637884086151b30fe12db52fbaf5eb.jpg",
"status": "",
"created_at": "2018-02-27 02:25:36",
"updated_at": "2018-02-27 02:25:36",
"destination_id": "182",
"is_cover": "0",
"url": "https://api.xplorpal.com/upload/images/300x300/6d637884086151b30fe12db52fbaf5eb.jpg"
}
},
{
"id": 183,
"title": "One Day Private Beijing Tour to Mutianyu Great Wall and Summer Palace ",
"price": "197",
"duration": "8",
"duration_type": "1",
"cover_image": {
"id": 305,
"img_path": "upload/images",
"img_file": "1f8a09ddffb80ef9232f3511893ae5c4.jpg",
"status": "",
"created_at": "2018-02-27 02:22:19",
"updated_at": "2018-03-01 23:01:55",
"destination_id": "183",
"is_cover": "0",
"url": "https://api.xplorpal.com/upload/images/300x300/1f8a09ddffb80ef9232f3511893ae5c4.jpg"
}
}
]
}
我需要反序列化
所以我写了这个模型
public class CoverImage
{
public int id { get; set; }
public string img_path { get; set; }
public string img_file { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string destination_id { get; set; }
public string is_cover { get; set; }
public string url { get; set; }
}
public class Result
{
public int id { get; set; }
public string title { get; set; }
public string price { get; set; }
public string duration { get; set; }
public string duration_type { get; set; }
public CoverImage cover_image { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
并尝试这样
var responseExperiences = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(content);
但是当我运行项目时,出现此错误:
无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.IEnumerable`1 [TravelApp.Models.GettingExperiences + Results]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化。 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型数组或列表),可以从JSON对象反序列化。还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。
我该如何解决?
答案 0 :(得分:1)
您的API返回的对象只有一个名为result
的属性,而不是集合。您应该反序列化为RootObject
对象。
答案 1 :(得分:1)
您的JSON显示了一个与result
相对应的对象RootObject
。
但是您正在尝试反序列化IEnumerable<>
的数组(RootObject
)
您应该使用它来反序列化显示的JSON:
JsonConvert.DeserializeObject<RootObject>(content);
答案 2 :(得分:1)
您的api返回一个名为 result 的单个对象,而不是您需要简单地像单个对象一样取消精化的集合。
var responseExperiences = JsonConvert.DeserializeObject<RootObject>(content);