Question

I have been battling with this for few hours and I can't figure out a solution. Using JSON.NET, I'm trying to deserialize some data to one or another derived class, BUT I want to target the right derived class based on a field that actually is in those data...

Here is a simplified example :

public class BaseFile {
    public string Name{get;set;}
}

public class Directory : BaseFile {
    public int FileSize {get;set;}
}

public class Video : BaseFile {
    public int  Duration{get;set}
}

I receive those JSON formatted data :

{
  "files": [
    {
      "content_type": "application/x-directory", 
      "size": 566686478
    }, 
    {
      "content_type": "video/x-matroska", 
      "duration": 50
    }
}

Now, I want to use JSON.NET, based on the content_type field, to instantiate either a Directory object (if the content_type is application/x-directory) or a Video object (if the content_type is video/x-matroska).

The simple solution is to deserialize all the content to the base class, and then transform those into their respective derived classes, but I don't find this effective so I'm wondering if there's another solution out there !

Thank you in advance for your input(s).

Was it helpful?

Solution

A friend of mine pointed me this post that solves my problem :

Deserializing heterogenous JSON array into covariant List<> using JSON.NET

I just tried it and for my case, the adapted code is written like this :

private BaseFile Create(Type objectType, JObject jObject)
{
    var type = (string)jObject.Property("content_type");
    switch (type)
    {
        case "application/x-directory":
            return new Directory();
        case "video/x-matroska":
            return new Video();
        default:
            return new BaseFile();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top