I'm looking to convert between a YAML file, and JSON. This was really difficult to find any information on.
If you do not need the features of Json.NET, you can also use the Serializer class directly to emit JSON:
// now convert the object to JSON. Simple!
var js = new Serializer(SerializationOptions.JsonCompatible);
var w = new StringWriter();
js.Serialize(w, o);
string jsonText = w.ToString();
You can check two working fiddles here:
It is possible to do this by using the built-in JSON library along with YamlDotNet. It wasn't apparent in the YamlDotNet documentation, but I found a way to do it rather simply.
// convert string/file to YAML object
var r = new StreamReader(filename);
var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
var yamlObject = deserializer.Deserialize(r);
// now convert the object to JSON. Simple!
Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();
var w = new StringWriter();
js.Serialize(w, yamlObject);
string jsonText = w.ToString();
I was surprised this worked as well as it did! JSON output was identical to other web based tools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With