YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

Questions about Custom Serialization

Open cd-zhang2020 opened this issue 1 year ago • 2 comments

Hello,Is it possible to add attributes to specified fields to implement a custom serialization and deserialization method?

For example Newtonsoft.Json

[JsonConverter(typeof(CustomConverter))]

var serializer = new SerializerBuilder() .WithTypeConverter(new CustomConverter()) .Build();

I use the above code to customize the serialization, but this is a global method

cd-zhang2020 avatar Jan 08 '24 01:01 cd-zhang2020

Not that I’m aware of. You’d need to have multiple builders to do different type converters like your asking about.

EdwardCooke avatar Jan 08 '24 17:01 EdwardCooke

@EdwardCooke Thank you for your answer,The functionality I want to implement cannot be handled with different types converters。

For example

serverConnector:
   id: server1
   addresses:
     - 127.0.0.1:8091
   protocol: grpc
   connectTimeout: 500ms
   messageTimeout: 5s
   connectionIdleTimeout: 60s
   serverSwitchInterval: 10m
   reconnectInterval: 500ms

Deserialize the string 500ms into the number 500, and deserialize the string 5s into the number 5000,I can't convert all strings to numbers

cd-zhang2020 avatar Jan 09 '24 01:01 cd-zhang2020

I’ll work on adding this feature.

EdwardCooke avatar Jul 08 '24 04:07 EdwardCooke

You can now specify a custom type converter on the property using the YamlConverter attribute. Be sure to register the converter with the serializer builder so it's used. In the AcceptsType method, just return false.

Here's the tests that show how to do it.

https://github.com/aaubry/YamlDotNet/blob/master/YamlDotNet.Test/Serialization/TypeConverterAttributeTests.cs

EdwardCooke avatar Jul 14 '24 17:07 EdwardCooke