0

I have the following classes

    class Configuration
    {
        
        public IConverter converter { get; set; }

    }


    public class HtmlConverter : IConverter
    {
        public string Convert()
        {
            return "HTML Convertter";
        }
    }

    public class JsonConverter : IConverter
    {
        public string Convert()
        {
            return "json Convertter";
        }
    }

    public interface IConverter
    {
        string Convert();
    }

and myjson file is

{
  "Configuration": {
    "Converter": "HtmlConverter"
  }
}

from the JSON file, I want to create the Configuration object.

in json file if converter is set to "HtmlConverter" then the HtmlConvert object should be created and if "JsonConverter" is set then JsonConverter object should be created.


Configuration  config = JsonConvert.DeserializeObject<Configuration>(jsonString);
3
  • Your JSON root object has a property "Configuration", your root C# class (Configuration) only has a property "Converter" (which doesn't exist in your JSON's root object). Commented Nov 19, 2021 at 10:27
  • 1
    You will need to write your own Json.NET contract-resolver to implement this logic. Commented Nov 19, 2021 at 10:28
  • Easiest way to create a converter for a simple file like yours is creating a new class and then copying the json string to the clipboard and then go to "paste" -> "as json class" in visual studio. VS will then create a model which can easily be serialized without any more implementation Commented Nov 19, 2021 at 10:48

1 Answer 1

1

I think here you need to use some factory patterns. For example, your class Configuration can be like this

public class Configuration
{
    public string Convertor { get; set; }
    public IConverter Create()
    {
        IConverter instance = (IConverter)Activator.CreateInstance("MyAssembly", $"MyNamespace.{Convertor}").Unwrap();
        if (instance == null)
        {
            throw new Exception("Convertor not found");
        }
        return instance;
    }

}

And you will use this in this way.

Configuration config = JsonConvert.DeserializeObject<Configuration>(jsonString);
var converter = config.Create();

But If you do not want to use reflection, you can use some if/else or switch statements. But the main idea is to use factory patterns.

Also your json file should look like this

{
   "Convertor": "JsonConverter"
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.