2

我正在使用 YamlDotNet 库来序列化 Yaml 中的一些对象。我在 Guid 属性的序列化方面遇到了一些问题。Guid 属性的序列化生成空括号(例如:{})

请参阅下面的代码

Dim l As New List(Of Person)
l.Add(New Person() With {.Firstname = "MyFirstName", .Lastname = "MyLastName", .Id = Guid.NewGuid()})

Using sw As New StreamWriter("output.yaml", False)
    Dim serializer = New Serializer()
    serializer.Serialize(sw, l)
End Using

此代码将输出:

- Id: {}
  Firstname: MyFirstName
  Lastname: MyLastName

与班级:

Public Class Person
    Public Property Id As Guid
    Public Property Frstname As String
    Public Property Lastname As String
End Class

我错过了什么还是图书馆的问题?

4

1 回答 1

0

您可以定义一个自定义转换器以在需要自定义类型的序列化时使用。转换器需要实现IYamlTypeConverter,并在Serializeror上注册Deserializer。以下是此类转换器的示例:

Public Class GuidConverter
    Implements IYamlTypeConverter

    Public Function Accepts(type As Type) As Boolean Implements IYamlTypeConverter.Accepts
        Return type = GetType(Guid)
    End Function

    Public Function ReadYaml(parser As IParser, type As Type) As Object Implements IYamlTypeConverter.ReadYaml
        Dim reader = New EventReader(parser)
        Dim scalar = reader.Expect(Of Scalar)()
        Return Guid.Parse(scalar.Value)
    End Function

    Public Sub WriteYaml(emitter As IEmitter, value As Object, type As Type) Implements IYamlTypeConverter.WriteYaml
        emitter.Emit(New Scalar(value.ToString()))
    End Sub
End Class

用法很简单:

Dim serializer = New Serializer()
serializer.RegisterTypeConverter(New GuidConverter())
serializer.Serialize(Console.Out, New With {.id = Guid.NewGuid()})

你可以在这里看到一个完整的例子

于 2014-10-13T22:35:04.173 回答