Zyberzero
Zyberzero

Reputation: 1604

Deserializing inherited classes

I want to send parameter-settings from a backendapplication to the frontend. I also need to be able to have different type of parameters (Portnumbers, folders, static strings and such).

So I've designed a baseclass, Parameter as such:

public abstract class Parameter
{
    public abstract bool isValid();
}

Let's say that we have two types of folder parameters:

public abstract class Folder : Parameter
{
    public string folderName { get; set; }

    protected Folder(string folderName)
    {
        this.folderName = folderName;
    }
}

public class ReadWriteFolder : Folder
{
    public ReadWriteFolder(string folderName) : base(folderName)
    {
    }

    public override bool isValid()
    {
        return isReadable() && isWritable();
    }
}

public class ReadFolder : Folder
{
    public ReadFolder(string folderName) : base(folderName)
    {
    }

    public override bool isValid()
    {
        return isReadable();
    }
}

This is used from a WebAPI, so this is my controller:

public Dictionary<String, Parameter> Get()
{ 
    Dictionary<String, Parameter> dictionary  = new Dictionary<String, Parameter>();
    dictionary.Add("TemporaryFiles", new ReadWriteFolder("C:\\temp\\"));
    dictionary.Add("AnotherTemporaryFiles", new ReadWriteFolder("D:\\temp\\"));

    return dictionary;
}

This yields the following JSON-serialisation: {"TemporaryFiles":{"folderName":"C:\\temp\\"},"AnotherTemporaryFiles":{"folderName":"D:\\temp\\"}} which seems reasonable.

My question is this: How can I deserialize this back into the original types? Or change the serialization into something that is more easy to deserialize?

Upvotes: 0

Views: 2681

Answers (1)

Gene
Gene

Reputation: 1585

What are you using for serialization? If it's JSON.Net (which many here would suggest!), there's a number of realted questions:

how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET

But the crux is the type name handling, which will decorate the elements with the type information to be able to deserialize them:

 JsonSerializerSettings settings = new JsonSerializerSettings
 {
    TypeNameHandling = TypeNameHandling.All
 };

string strJson = JsonConvert.SerializeObject(dictionary, settings);

And then you should be able to deserialize directly.

var returnDictionary = JsonConvert.DeserializeObject<Dictionary<String, Parameter>>(strJson, settings)

Upvotes: 2

Related Questions