如何使用YamlDotNet将JSON转换为YAML

时间:2016-03-17 12:49:47

标签: c# json yaml yamldotnet

我正在尝试使用YamlDotNet将JSON转换为YAML。这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"swagger\":\"2.0\",\"info\":{\"title\":\"UberAPI\",\"description\":\"MoveyourappforwardwiththeUberAPI\",\"version\":\"1.0.0\"},\"host\":\"api.uber.com\",\"schemes\":[\"https\"],\"basePath\":\"/v1\",\"produces\":[\"application/json\"]}";
        var swaggerDocument = JsonConvert.DeserializeObject(json);

        var serializer = new YamlDotNet.Serialization.Serializer();

        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, swaggerDocument);
            var yaml = writer.ToString();
            Console.WriteLine(yaml);
        }
    }
}

这是我提供的JSON:

{
   "swagger":"2.0",
   "info":{
      "title":"UberAPI",
      "description":"MoveyourappforwardwiththeUberAPI",
      "version":"1.0.0"
   },
   "host":"api.uber.com",
   "schemes":[
      "https"
   ],
   "basePath":"/v1",
   "produces":[
      "application/json"
   ]
}

这是我期待的YAML:

swagger: '2.0'
info:
  title: UberAPI
  description: MoveyourappforwardwiththeUberAPI
  version: 1.0.0
host: api.uber.com
schemes:
  - https
basePath: /v1
produces:
  - application/json

然而,这是我得到的输出:

swagger: []
info:
  title: []
  description: []
  version: []
host: []
schemes:
- []
basePath: []
produces:
- []

我不知道为什么所有属性都是空数组。

我也尝试了类似的反序列化和序列化:

var specification = JsonConvert.DeserializeObject<SwaggerDocument>(json);
...
serializer.Serialize(writer, swaggerDocument, typeof(SwaggerDocument));

但这会产生

{}

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:5)

您实际上并不需要将JSON反序列化为强类型对象,您也可以使用动态Expando对象将JSON转换为YAML。这是一个小例子: -

var json = @"{
        'Name':'Peter',
        'Age':22,
        'CourseDet':{
                'CourseName':'CS',
                'CourseDescription':'Computer Science',
                },
        'Subjects':['Computer Languages','Operating Systems']
        }";

        var expConverter = new ExpandoObjectConverter();
        dynamic deserializedObject = JsonConvert.DeserializeObject<ExpandoObject>(json, expConverter);

        var serializer = new YamlDotNet.Serialization.Serializer();
        string yaml = serializer.Serialize(deserializedObject);

您可以看到两种方法的详细说明,即使用强类型对象和动态对象here

答案 1 :(得分:2)

我认为当json反序列化返回JObject时会出现问题。看起来像yaml序列化器并不喜欢它。

我按照你提到的JsonConvert.DeserializeObject<SwaggerDocument>(json)使用了指定类型的反序列化,这就是我得到的

Swagger: 2.0
Info:
  Title: UberAPI
  Description: MoveyourappforwardwiththeUberAPI
  Version: 1.0.0
Host: api.uber.com
Schemes:
- https
BasePath: /v1
Produces:
- application/json

这是我的全部代码:

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"Swagger\":\"2.0\",\"Info\":{\"Title\":\"UberAPI\",\"Description\":\"MoveyourappforwardwiththeUberAPI\",\"Version\":\"1.0.0\"},\"Host\":\"api.uber.com\",\"Schemes\":[\"https\"],\"BasePath\":\"/v1\",\"Produces\":[\"application/json\"]}";
        var swaggerDocument = JsonConvert.DeserializeObject<SwaggerDocument>(json);

        var serializer = new YamlDotNet.Serialization.Serializer();

        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, swaggerDocument);
            var yaml = writer.ToString();
            Console.WriteLine(yaml);
        }
    }
}

public class Info
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Version { get; set; }
}

public class SwaggerDocument
{
    public string Swagger { get; set; }
    public Info Info { get; set; }
    public string Host { get; set; }
    public List<string> Schemes { get; set; }
    public string BasePath { get; set; }
    public List<string> Produces { get; set; }
}

<强>更新

这里有两个问题。

使用字段反序列化类时,默认情况下json.net在完成工作时不会考虑它们。为此,我们必须通过创建自定义合约解析程序来自定义反序列化过程。我们可以通过

轻松完成
var swaggerDocument = JsonConvert.DeserializeObject<SwaggerDocument>(json, new JsonSerializerSettings
{
    ContractResolver = new MyContractResolver()
});

public class MyContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Select(p => base.CreateProperty(p, memberSerialization))
            .Union(type.GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Select(f => base.CreateProperty(f, memberSerialization)))
            .ToList();
        props.ForEach(p => { p.Writable = true; p.Readable = true; });
        return props;
    }
}

当我们想要用字段序列化类时,有第二个问题。来自字段的值不会包含在yaml结果中。我还没有想出如何处理这个问题。

您是否必须使用Swashbuckle.Swagger类型,或者您可以为此类型创建包装器/装饰器/ DTO?

我希望它可以帮到你。

答案 2 :(得分:2)

您可以将JObject转换为YamlDotNet可以序列化的更简单的对象:

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"swagger\":\"2.0\",\"info\":{\"title\":\"UberAPI\",\"description\":\"MoveyourappforwardwiththeUberAPI\",\"version\":\"1.0.0\"},\"host\":\"api.uber.com\",\"schemes\":[\"https\"],\"basePath\":\"/v1\",\"produces\":[\"application/json\"]}";
        var swaggerDocument = ConvertJTokenToObject(JsonConvert.DeserializeObject<JToken>(json));

        var serializer = new YamlDotNet.Serialization.Serializer();

        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, swaggerDocument);
            var yaml = writer.ToString();
            Console.WriteLine(yaml);
        }
    }

    static object ConvertJTokenToObject(JToken token)
    {
        if (token is JValue)
            return ((JValue)token).Value;
        if (token is JArray)
            return token.AsEnumerable().Select(ConvertJTokenToObject).ToList();
        if (token is JObject)
            return token.AsEnumerable().Cast<JProperty>().ToDictionary(x => x.Name, x => ConvertJTokenToObject(x.Value));
        throw new InvalidOperationException("Unexpected token: " + token);
    }
}

答案 3 :(得分:0)

我正在使用以下代码从JSON构建Yaml元素并将其写入文件。

代码如下:

    public static void BuildParametrizedYAML(string element, string element1)
    {
        var jsonBreakers = @"
        {
            'watchers' : {
                'timer' : '10',
                'watcherPool' : '5',
                's3fileExtension' : '.avr.gz',
                'maxRetriesTask' : '3',
                'telemetryFolder' : '/data',
                'telemetryProcessor' : { 
                    'url' : '"+ element1 + @"'
                },
                'breakers' : 
                [
                    {
                        'breakerId' : 'COMMANDER',
                        'firstRetryTimeout' : '1000',
                        'secondRetryTimeout' : '6000',
                        'retries' : '5'
                    },
                    {
                        'breakerId' : 'PROCESSOR',
                        'firstRetryTimeout' : '1000',
                        'secondRetryTimeout' : '6000',
                        'retries' : '30'
                    }
                ],
                'servers' : 
                [
                    {
                        'serverId' : 'vmax',
                        'url' : '"+ element + @"'
                    }
                ]
            }
        }";

        var expConverter = new ExpandoObjectConverter();
        dynamic deserializedObject = JsonConvert.DeserializeObject<ExpandoObject>(jsonBreakers, expConverter);           
        var serializer = new Serializer();
        string JSONContent = serializer.Serialize(deserializedObject);

        var streamLoad = new StringReader(JSONContent);
        var stream = new YamlStream();
        stream.Load(streamLoad);

        using (TextWriter writer = File.CreateText("application.yml"))
        {
            stream.Save(writer, false);
        }
    }

这是输出:

watchers:
  timer: 10
  watcherPool: 5
  s3fileExtension: .avr.gz
  maxRetriesTask: 3
  telemetryFolder: /data
  telemetryProcessor:
    url: TELEMETRYPROCESSORURL
  breakers:
  - breakerId: COMMANDER
    firstRetryTimeout: 1000
    secondRetryTimeout: 6000
    retries: 5
  - breakerId: PROCESSOR
    firstRetryTimeout: 1000
    secondRetryTimeout: 6000
    retries: 30
  servers:
  - serverId: vmax
    url: TELEMETRYWATCHERVMAXURL
...

请随时给我写信。