我正在使用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
我错过了什么或这是图书馆的问题吗?
答案 0 :(得分:0)
您可以定义要在自定义类型序列化时使用的自定义转换器。转换器需要实施IYamlTypeConverter,并在Serializer
或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()})