2

I'm trying to serialize enum in json. If Enum Value is "Male" and "Female". I want it as "M" and "F". Here is the code sample,it works for XmlSerializer but i need to make it work for JsonSerializer

public enum Gender { [EnumMember(Value = "M"), XMLEnum("M")] Male, [EnumMember(Value = "F"), XMLEnum("F")] Female } 

P.S. I'm using ServiceStack as Json Serializer

1 Answer 1

2

An nice approach would be to use the SerializeFn routine of the ServiceStack configuration object, and configure your custom serialization for the Gender enum.

var person = new Person() { FullName = "John Johnson", Gender = Gender.Male }; JsConfig<Gender>.SerializeFn = c => c.Equals(Gender.Male) ? "M" : "F"; var result = person.ToJson(); // {"FullName":"John Johnson","Gender":"M"} 

Update: Since we determined you can't upgrade your ServiceStack.Text library to 4+, and you would definitely like to leverage the existing enummember attributes, here is a solution that skips the SerializeFn approach completely.

You can install an additional nuget package called ServiceStack.Text.EnumMemberSerializer, which allows you to use the existing enummember attributes. Here is the code to make it work:

new EnumSerializerConfigurator() .WithEnumTypes(new Type[] { typeof(Gender) }) .Configure(); JsConfig.Reset(); var result = JsonSerializer.SerializeToString(person); // {"FullName":"John Johnson","Gender":"M"} 

I have tested with ServiceStack.Text 3.9 and it worked.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for the reply. I tried the same thing but doesn't seem to be working for me.
Can u update the question with the exact code that you use to serialize the enum? in addition you can also specify the version of the ServiceStack library, since that could also be an issue.
It still gives me "Male" instead of "M". I'm using Product Version: 3.9.59.0
I just checked that version and there is definitely an issue. However, when i use the latest version it works like a charm. Can you update the package to use the latest version of ServiceStack.Text?
Zen Coder. Thank You. Your code seems to be working with Version 4.0. Is it available for free or do I have to pay for it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.