How to convert YAML to JSON?

霸气de小男生 提交于 2019-12-07 10:56:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!