Reputation: 65
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);
Upvotes: 0
Views: 135
Reputation: 34
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"
}
Upvotes: 1