[英]How can I create a custom converter similar to Newtonsoft using system.text.json?
[英]Create a custom NewtonSoft JSon Converter
我有以下使用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();
}
}
這不起作用。 有誰知道我應該如何創建轉換器?
您的JSON標記與您的.NET類不匹配,因此反序列化失敗,原因如下:
ListingData.Id
是一個整數,但您的JSON使用字母數字id
值 listings
數組 修復listings[n].data.id
值或將listings[n].data.id
的數據類型更改為String
,並清除JSON語法錯誤,您將全部設置ListingData.Id
。
你真的不需要自定義轉換器; 你的標記非常標准。 這是有效的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中修復的所有內容。 請確保正確調試您的代碼,這些問題通常會解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.