dahomey-technologies/Dahomey.Cbor

Question : LowerCase

Closed this issue · 3 comments

Hi,

See below code block. all properties that i need to serialize/deserialize need to be lowercase.
Is there anyway i can register a contract of some sort for all types, so i can avoid using CborProperty?

I'd like to keep my classes as clean as possible. Thank you for any help.

        [CborProperty("from")]
        public Address From { get; }

        [CborProperty("to")]
        public Address To { get; }

Hi jonassix,

Yes, it's totally possible.
However, you need to implement 3 interfaces:

        public class LowerCaseNamingConvention : INamingConvention
        {
            public string GetPropertyName(string name)
            {
                return name.ToLowerInvariant();
            }
        }

        public class LowerCaseObjectMappingConvention : IObjectMappingConvention
        {
            private readonly IObjectMappingConvention defaultObjectMappingConvention = new DefaultObjectMappingConvention();
            private readonly INamingConvention lowerCaseNamingConvention = new LowerCaseNamingConvention();

            public void Apply<T>(SerializationRegistry registry, ObjectMapping<T> objectMapping) where T : class
            {
                defaultObjectMappingConvention.Apply<T>(registry, objectMapping);
                objectMapping.SetNamingConvention(lowerCaseNamingConvention);
            }
        }

        public class LowerCaseObjectMappingConventionProvider : IObjectMappingConventionProvider
        {
            private readonly IObjectMappingConvention _objectMappingConvention = new LowerCaseObjectMappingConvention();

            public IObjectMappingConvention GetConvention(Type type)
            {
                return _objectMappingConvention;
            }
        }

Then you need to setup the provider in CborOptions.

CborOptions.Default.Registry.ObjectMappingConventionRegistry.RegisterProvider(new LowerCaseObjectMappingConventionProvider());

You can also decide to instantiate a new instance of CborOptions and to pass it to Cbor serialization methods.

Let me know if you have any issue with this solution.

Important:
If you already implement another IObjectMappingConvention, you shoud configure the naming convention in the same IObjectMappingConvention, because you can have only one convention for each type and the framework will use the first one returned by IObjectMappingConventionProvider.GetConvention

Works perfectly. Thanks!