[英]Deserealizing JSON object using Newtonsoft.Json
我有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对象反序列化。
我该如何解决?
您的API返回的对象只有一个名为result
属性,而不是集合。 您应该反序列化为RootObject
对象。
您的JSON显示一个与RootObject
对应的对象result
。
但是您正在尝试反序列化RootObject
的数组 ( IEnumerable<>
)
您应该使用它来反序列化显示的JSON:
JsonConvert.DeserializeObject<RootObject>(content);
您的api返回一个名为result的单个对象, 而不是一个需要简单地像单个对象一样反序列化的集合。
var responseExperiences = JsonConvert.DeserializeObject<RootObject>(content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.