Jil icon indicating copy to clipboard operation
Jil copied to clipboard

Add TreatEnumerationAs to the Options

Open MERamadan opened this issue 7 years ago • 2 comments

Add a TreatEnumerationAs property to the Options class, to allow controlling how the Enums are serialized/deserialized in all the project without the need to add the JilDirectiveAttribute attribute to each Enum field in each data-contract.

In addition, the developer still can add JilDirectiveAttribute to a field, when need to change a field behavior from the default behavior defined by the Options class.

This feature will be very useful when using Jil as the JSON serializer in WebApi projects, by allowing the project owners a full control to Jil behavior without the need to change the data-contract models.

MERamadan avatar Dec 05 '17 19:12 MERamadan

+1

cubed-it avatar Feb 02 '18 08:02 cubed-it

Instead of having a JilDirective added at the top of model classes, I would like to propose something as

string jilJson = JSON.Serialize(yourObject, Options.TreatEnumerationAsInt32);

Newtonsoft already converts enums to int as I have seem in some of its serializations. Convert enum to int might be wrong - I am not sure.

But on the other hand, if developers want to migrate from Newtonsoft to Jil without loosing their current newtonsoft serialization data format, you guys could add an option in Jil for serializing enums to integers.

By avoiding Jil directives / data annotations we would have cleaner DTO / model classes.

Here is some expected behavior

Datatype Newtonsoft serialized string Jil current serialized string Jil expected serialized string
enum DeliveryType.OneWeek = 0 "DeliveryType": 0 "DeliveryType": "OneWeek" "DeliveryType": 0

I have noticed we can import System.Runtime.Serialization at enum type but that creates some noise in model class and Jil would generate string representation of the value "DeliveryType": "0" instead of a integer value "DeliveryType": 0

namespace Application.DTOs
{
    using System.Runtime.Serialization;
    public enum DeliveryType
    {
        [EnumMember(Value="0")] OneWeek = 0, // this produces "0" and not 0
        [EnumMember(Value="1")] SameDay = 1, // this produces "1" and not 1
        [EnumMember(Value="2")] Premium = 2 // this produces "2" and not 2
    }
}

What do you think @kevin-montrose ?

juniormayhe avatar May 25 '19 11:05 juniormayhe