YamlDotNet
YamlDotNet copied to clipboard
Question: Serialize dynamic dictionary
I'm trying to serialize an object that contains a property which is a dictionary of type Dictionary<string, object>.
Basically this property will be an arbitrary json object, which can have different shapes, but my function should be unaware of the shape and simply accept the input and serialize it.
So basically, something in the format:
public class Input {
public string Name {get;set;}
public Dictionary<string, object> Annotation {get;set;}
}
The issue I have, is when I try to serialize this class to Yaml, the property Annotation contains the value: KindObject.
Any idea how I can better use the library to achieve this feature?
Thank you for the support.
Upon further debugging, I've found that the issue is elsewhere. Serializing an instance of this class directly is not an issue, the problem is the json serialization in between.
I have some E2E tests and I think the request dto is causing the issue.
My request dto is an instance of Input. When inspecting the object, I can see that the value of the property is a JsonElement.

Is maybe the case that YamlDotNet is not able to serialize a JsonElement?
I don't know what is a JsonElement, but assuming that it is a representation of part of a JSON syntax, you will need to register a IYamlTypeConverter
that will take care of converting it to YAML. I can't really help much because the implementation of the converter is dependent of what your goal is.
I have started a library with a IYamlTypeConverter for System.Text.Json here, https://github.com/IvanJosipovic/YamlDotNet.System.Text.Json