How to convert JSON to YAML using YamlDotNet

Viewed 9398

I am trying to convert JSON to YAML using YamlDotNet. This is the code I have:

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);
        }
    }
}

This is the JSON I provide:

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

This is the YAML I expect:

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

However, this is the output I get:

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

I don't have a clue why all properties are empty arrays.

I also tried typed deserialization and serialization like this:

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

But that produces

{}

Any help is much appreciated.

6 Answers

FWIW I wrote a nuget library to make YamlDotNet work great with Json.Net, honoring all of the JSON.net serialization attributes.

    var yaml = YamlConvert.SerializeObject(obj);
    var obj2 = YamlConvert.DeserializeObject<T>(yaml);

It works by adding a YamlDotNet type serialization class for JTokens (JObject/JArray/JValue)

    var serializer = new SerializerBuilder()
         .WithTypeConverter(new JTokenYamlConverter())
         .Build();

Use Cinchoo ETL - an open source library to do such conversion easily.

using (var r = new ChoJSONReader("*** YOUR JSON FILEPATH ***"))
{
    using (var w = new ChoYamlWriter("*** YAML FILE OUTPUT PATH ***").SingleDocument())
    {
        w.Write(r);
    }
}

Output:

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

Sample fiddle: https://dotnetfiddle.net/rbOD0o

Disclaimer: I'm the author of this library.

I'm using the following piece of code to build a Yaml element from a JSON and writing it to a file.

Here is the code:

    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);
        }
    }

And here is the output:

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
...

Feel free to write me about this.

Related