问题
I'm looking to convert between a YAML file, and JSON. This was really difficult to find any information on.
回答1:
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:
- Convert YAML to JSON
- Convert YAML to JSON using Json.NET
回答2:
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, o);
string jsonText = w.ToString();
I was surprised this worked as well as it did! JSON output was identical to other web based tools.
来源:https://stackoverflow.com/questions/30364884/how-to-convert-yaml-to-json