How to serialize Object for yaml in . NET?

Asked

Viewed 35 times

3

We can serialize objects (I’ll use as an example C#) for XML, using the class System.Xml.Serialization.XmlSerializer, for example:

var obj = new AlgumaClasse();

System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
System.IO.StringWriter writer = new System.IO.StringWriter();
xmlSerializer.Serialize(writer, obj);
var xmlString = writer.ToString();

Or to json using for example the package Newtonsoft, with class Newtonsoft.Json.JsonConvert.SerializeObject:

var obj = new AlgumaClasse();
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

My question is: how to serialize an object to the format yaml?

Is there any class or package that does this similarly to the above examples?

  • worked out?.....

  • 1

    Yes, I used the "Yamldotnet.Netcore" and attended well, thank you :)

1 answer

1


There are packages that can solve your problem:

Base Class:

public class ExampleObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Example
{
    public int Id { get; set; }
    public Guid Version { get; set; }
    public string Name { get; set; }
    public List<string> Sources { get; set; }
    public ExampleObject ExampleObject { get; set; }
}

How to use?

Example example = new Example();
example.Id = 1;
example.Version = Guid.NewGuid();
example.Name = "Example";
example.Sources = new System.Collections.Generic.List<string>
{
    "1",
    "2"
};
example.ExampleObject = new ExampleObject
{
    Id = 2,
    Name = "Object"
};

var serializer = new SerializerBuilder().Build();
var yaml = serializer.Serialize(example);

Upshot:

Id: 1
Version: 310bf8c6-87e1-4ea0-84d7-25c615d5d4b8
Name: Example
Sources:
- 1
- 2
ExampleObject:
  Id: 2
  Name: Object

Github: Yamldotnet/wiki

Using custom type converters with C# and Yamldotnet, part 1


Another interesting package:

How to use?

var serializer = new SharpYaml.Serialization.Serializer();
var yaml = serializer.Serialize(example);

Upshot:

!ConsoleApp1.Example,%2520ConsoleApp1,%2520Version=1.0.0.0,%2520Culture=neutral,%2520PublicKeyToken=null
ExampleObject:
  Id: 2
  Name: Object
Id: 1
Name: Example
Sources:
  - 1
  - 2
Version: 38d0a3a1-c963-4805-86fc-6bcb838d23d7

Github: Sharpyaml

Browser other questions tagged

You are not signed in. Login or sign up in order to post.