facebook-csharp-sdk / simple-json

JSON library for .NET 2.0+/SL4+/WP7/WindowsStore with optional support for dynamic and DataContract
MIT License
382 stars 143 forks source link

DataContract serialization of enum member to/from string #77

Open Deepscorn opened 7 years ago

Deepscorn commented 7 years ago

What I mean:

[DataContract]
    public enum AnimalKeeper
    {
        [DataMember(Name = "no keeper")]
        None,
        [DataMember(Name = "Mary Rose")]
        Mary,
        [DataMember(Name = "Tom The Third")]
        Tom,
        [DataMember(Name = "Simply, Todd")]
        Todd
    }

[DataContract]
    public class Animal : JsonResponse
    {
        [DataMember(Name = "animal keeper")]
        public AnimalKeeper Keeper { get; private set; }

        [NotNull]
        [DataMember(Name = "animal color")]
        public string Color { get; private set; }
}

Suppose, we have following instance of Animal: new Animal() { Keeper = "Mary Rose, Color = "red" }

I uncomment

#define SIMPLE_JSON_DATACONTRACT

to make DataContract/DataMember attributes used in serialization.

Expecting serialized result: { "animal keeper" : "Mary Rose", "animal color" : "red" }

Actual result { "animal keeper" : 1, "animal color" : "red" }

PS I came from java and there we successfully used (for example) com.google.api.client.util.Value attribute to specify [de]serialized string value for each enum member:

public enum CardStatus {
    @Value("active")
    ACTIVE,
    @Value("expired")
    EXPIRED,
    @Value("blocked")
    BLOCKED
}

public class Card {
    @Key("status")
    private CardStatus status;
    @Key("card id")
    private String id;
}

So, serialized example of Card: { "card id" : "101010", "status" : "expired" }

PS com.google.api.client.util.Value is in com.google.http-client:google-http-client-android:1.22.0 or com.google.http-client:google-http-client-jackson2:1.22.0

PS I tested code of merge request #64 and it gave me: { "animal color" : "red", "animal keeper" : "Mary" } As you see, sadly, DataMember attribute ignored