JSON to YAML conversion (for .NET application)

Here are a few different ways to convert JSON to YAML in C#.

For JSON serialization/deserialization I have used Newtonsoft's Json.NET library and for YAML serialization/deserialization I have used YamlDotNet library.

  • Using strongly typed C# object

    • Create the following classes to get the strongly typed object for JSON:-
    • public class Student
      {
      public string Name { get; set; }
      public int Age { get; set; }
      public CourseDetails CourseDet { get; set; }
      public List<string> Subjects { get; set; }
      }

      public class CourseDetails
      {
      public string CourseName { get; set; }
      public string CourseDescription { get; set; }
      }

    • All set to go, the below code shows how to convert JSON to YAML using the "Student" class object as an intermediate :-
    • var json = @"{
                      'Name':'Peter',
                      'Age':22,
                      'CourseDet':{
                              'CourseName':'CS',
                              'CourseDescription':'Computer Science',
                              },
                      'Subjects':['Computer Languages','Operating Systems']
                       }";

      var student = JsonConvert.DeserializeObject<Student>(json);

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

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

    • The value of "yaml" variable after executing the above code segment is :-

  • Using dynamic C# object

    • With dynamic object you don't need to create any of those classes as above, all you need to do is use the below code directly :-
      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);

      The output of "yaml" variable here will be same as that for the strongly typed object.


No comments:

Post a Comment