Replies: 1 comment
-
If you can't use tags, there's not much you can do. There's no way to know what the type is to deserialize it into. The only thing I can think of is to call the non generic Deserialize method and manually take the resulting object and generate your object from that. It's definitely not great, especially in larger yaml files, but this is probably the only way to go right now. Here's an example: var yaml = @"
tasks:
taskA:
type: ""taskA""
amount: 10
taskB:
type: ""taskB""
address: ""addressOfB""
";
var o = deserializer.Deserialize(yaml, typeof(object));
var tasks = new Tasks();
foreach (var tasksKVP in (Dictionary<object, object>)o)
{
//next level is taskA/taskB
foreach (var task in (Dictionary<object, object>)tasksKVP.Value)
{
var key = (string)task.Key;
var dictionary = ((Dictionary<object, object>)task.Value).ToDictionary(x => (string)x.Key, x => (string)x.Value);
ITask impl;
switch (dictionary["type"])
{
case "taskA":
impl = new TaskA
{
Amount = int.Parse(dictionary["amount"]),
Type = dictionary["type"]
};
break;
case "taskB":
impl = new TaskB
{
Address = dictionary["address"],
Type = dictionary["type"]
};
break;
default:
throw new NotImplementedException();
}
tasks.MyTasks[key] = impl;
}
}
var serializer = new SerializerBuilder().WithNamingConvention(YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention.Instance).Build();
Console.WriteLine(serializer.Serialize(tasks));
interface ITask
{
public string Type { get; set; }
}
class Tasks
{
public Tasks()
{
MyTasks = new Dictionary<string, ITask>();
}
public Dictionary<string, ITask> MyTasks { get; set; }
}
class TaskA : ITask
{
public string Type { get; set; }
public int Amount { get; set; }
}
class TaskB : ITask
{
public string Type { get; set; }
public string Address { get; set; }
} Output:
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello, and thank you for this wonderful API.
I'm struggling trying to have a dictionary with different items implementing the same interface. If I have TaskA and TaskB implementing ITask, I successfully serialize my .yml but can't deserialize it. I tried with IObjectFactory, but I 'don't have enough context to know which constructor to call. I also tried with INodeDeserializer, and had the same issue. The key of the dictionary is almost the type name. I can't use tag, because I'm not the only owner of the yaml.
Thank you for your help :)
Beta Was this translation helpful? Give feedback.
All reactions