[英]Deserializing different possible objects using the same class
嘗試使用 C# 反序列化 JSON 時遇到問題。
我有一個pagingObject類,它有一個items對象數組。 這個數組可以是許多不同的對象,每個對象都有不同的結構。
class pagingObject
{
public string href { get; set; }
public savedTrack[] items { get; set; } //this could be either savedTracks object or Tracks object, depending on request
public int limit { get; set; }
public string next { get; set; }
public int offset { get; set; }
public string previous { get; set; }
public int total { get; set; }
}
class savedTrack
{
public string added_at { get; set; }
public Track track { get; set; }
}
class Track
{
public Album album { get; set; }
public Artist[] artists { get; set; }
public string[] available_markets { get; set; }
public int disc_number { get; set; }
public int duration_ms { get; set; }
[JsonProperty(PropertyName = "explicit")]
public bool is_explicit { get; set; }
public External_ids external_id { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public int popularity { get; set; }
public string preview_url { get; set; }
public int track_number { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
我正在使用 Newtonsoft.Json 進行反序列化。
我如何告訴我的程序項目可能是上述對象之一( savedTracks或Tracks )?
先感謝您!
似乎您可以簡單地使用通用pagingObject<T>
作為基本模型:
class pagingObject<T>
{
public string href { get; set; }
public T[] items { get; set; }
public int limit { get; set; }
public string next { get; set; }
public int offset { get; set; }
public string previous { get; set; }
public int total { get; set; }
}
稍后您可以通過指定具體類型來反序列化 JSON,例如:
pagingObject<Truck> model = JsonConvert.DeserializeObject<pagingObject<Truck>>(jsonStr);
pagingObject<savedTrack> model = JsonConvert.DeserializeObject<pagingObject<savedTrack>>(jsonStr);
主要重新編輯,我沒有直接思考。
我相信您可以將 public savedTrack[] 項目更改為:
public object[] items
然后在您可以檢查 items 數組是否與您期望的任何一種對象類型匹配之后
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.