简体   繁体   中英

Deserializing different possible objects using the same class

I have run into a problem when trying to deserialize JSON using C#.

I have a pagingObject class which has an items object array. This array could be a number of different objects, each having different structures.

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; }
}

I am using Newtonsoft.Json to deserialize.

How can i tell my program that items could be either one of the said objects ( savedTracks or Tracks )?

Thank you in advance!

It seems that you may simply use the generic pagingObject<T> as a base model:

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; }
}

And later you may deserialize the JSON by specifying the concrete type, like:

pagingObject<Truck> model = JsonConvert.DeserializeObject<pagingObject<Truck>>(jsonStr);
pagingObject<savedTrack> model = JsonConvert.DeserializeObject<pagingObject<savedTrack>>(jsonStr);

Major re-edit, I wasn't thinking straight.

I believe you can change public savedTrack[] items into:

public object[] items

then after you can check if the items array matches either one of the object types you are expecting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM