简体   繁体   English

如何将 YAML 转换为 JSON?

[英]How to convert YAML to JSON?

I'm looking to convert between a YAML file, and JSON.我希望在 YAML 文件和 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:如果不需要 Json.NET 的特性,也可以直接使用 Serializer 类来发出 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.可以通过使用内置的 JSON 库和 YamlDotNet 来做到这一点。 It wasn't apparent in the YamlDotNet documentation, but I found a way to do it rather simply.这在 YamlDotNet 文档中并不明显,但我找到了一种相当简单的方法。

// 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. JSON 输出与其他基于 Web 的工具相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM