我有以下使用NewtonSoft JSon解析的JSon:
{
"page" : 0,
"listings" : [
{
"data" : { "name" : "Name 1", "id" : "id1" },
"media" : {
"images" : [
{ "title" : "image1", "url" : "http://www.d.com/image1" },
{ "title" : "image2", "url" : "http://www.d.com/image3" },
]
}
},
{
"data" : { "name" : "Name 2", "id" : "id2" },
"media" : {
"images" : [
{ "title" : "image3", "url" : "http://www.d.com/image3" },
{ "title" : "image4", "url" : "http://www.d.com/image4" },
]
}
},
}
C#对象如下:
public class Result {
[JsonProperty("page")]
public Int32 Page { get; set; }
[JsonProperty("listings")]
public List<Listing> Listings { get; set; }
} // PropertyResult
public class Listing {
[JsonProperty("data")]
public ListingData Data { get; set; }
[JsonProperty("media")]
public ListingMedia Media{ get; set; }
}
public class ListingData {
[JsonProperty("id")]
public Int32 Id { get; set; }
[JsonProperty("name")]
public String Name { get; set; }
}
public class ListingMedia {
[JsonProperty("images")]
public IList<ListingMediaImage> Images { get; set; }
}
public class ListingMediaImage {
[JsonProperty("title")]
public String Title { get; set; }
[JsonProperty("url")]
public String Url { get; set; }
}
我能够解析ResultPage但不能解析列表。
然后我尝试了转换器:
public class ResultConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return (objectType == typeof(Result));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
JObject jo = JObject.Load(reader);
Result result = jo.ToObject<Result>();
result.Listings.Data = jo.SelectToken("listings.data").ToObject<ResultData>();
result.Listings.Images = jo.SelectToken("listings.media").ToObject<ResultMedia>();
return result;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
这不起作用。 有谁知道我应该如何创建转换器?
答案 0 :(得分:3)
您的JSON标记与您的.NET类不匹配,因此反序列化失败,原因如下:
ListingData.Id
是一个整数,但您的JSON使用字母数字id
值listings
阵列修复listings[n].data.id
值或将ListingData.Id
的数据类型更改为String
,并清除JSON语法错误,您将全部设置完毕。
你真的不需要自定义转换器;你的标记非常标准。这是有效的JSON标记,可以反序列化到当前的.NET类中:
string json = @"{
""page"" : 0,
""listings"" : [{
""data"" : { ""name"" : ""Name 1"", ""id"" : ""1"" },
""media"" : {
""images"" : [
{ ""title"" : ""image1"", ""url"" : ""http://www.d.com/image1"" },
{ ""title"" : ""image2"", ""url"" : ""http://www.d.com/image3"" }
]
}
},
{
""data"" : { ""name"" : ""Name 2"", ""id"" : ""2"" },
""media"" : {
""images"" : [
{ ""title"" : ""image3"", ""url"" : ""http://www.d.com/image3"" },
{ ""title"" : ""image4"", ""url"" : ""http://www.d.com/image4"" }
]
}
}]
}";
var result = JsonConvert.DeserializeObject<Result>(json);
您的IDE /调试器提供了非常有用的错误消息。在这种情况下,我通过检查Newtonsoft库引发的错误,学习了我需要在JSON中修复的所有内容。请确保正确调试您的代码,这些问题通常会解决。