【发布时间】:2019-05-30 03:59:52
【问题描述】:
我在尝试使用 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 进行反序列化。
我如何告诉我的程序 items 可能是上述对象之一(savedTracks 或 Tracks)?
提前谢谢你!
【问题讨论】:
-
通过让两个类实现一个公共基类并反序列化为这种类型的列表。
-
但是我如何在 pagingObjects 中声明这个?与评论一致?
-
你知道反序列化时Json(
savedTrucks或Truck)里面有什么吗?还是你不知道? -
谢谢大家的帮助。我意识到可能的结果并不多,所以我只是通过为每个结果创建单独的 pagingObject 类来解决这个问题。这可能不是最聪明的解决方案,但它确实有效。 :)
标签: c# json deserialization