使用同一类反序列化不同可能的对象



我在尝试使用C#反序列化JSON时遇到了一个问题。

我有一个pagingObject类,它有一个项对象数组。这个数组可以是许多不同的对象,每个对象都有不同的结构。

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进行反序列化。

如何告诉我的程序项目可以是上述对象之一(savedTrackTracks)?

提前谢谢!

似乎可以简单地使用通用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);

主要是重新编辑,我没有想清楚。

我相信您可以将公共savedTrack[]项目更改为:

public object[] items

然后,在您可以检查items数组是否与您期望的对象类型之一匹配之后

最新更新