How to convert JSON to YAML using YamlDotNet

venerik picture venerik · Mar 17, 2016 · Viewed 7.1k times · Source

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.

Answer

Yatharth Varshney picture Yatharth Varshney · Feb 13, 2017

You don't actually need to deserialize JSON into strongly typed object you can convert JSON to YAML using dynamic Expando object as well. Here is a small example:-

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

You can see a detailed explanation of both methods i.e. using strongly typed object and dynamic object here.