2

Is it possible to serialize the enum as either a proper string value or the value specified by the EnumMember attribute rather than a number? It seems that JSON serialization ignores the Value property of EnumMember attribute. If I change WebMessageFormat to Xml it works fine, but I need to use JSON.

I have the following IIS-Hosted REST Service

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "test")]
    SomeObject Test();

SomeObject:

[DataContract]
public class SomeObject
{
    [DataMember]
    public SomeEnum FooBar
    {
        get;
        set;
    }
}

SomeEnum:

[DataContract]
public enum SomeEnum
{
    [EnumMember(Value = "FooValue")]
    [Description("FooDescription")]
    Foo,

    [EnumMember(Value = "BarValue")]
    [Description("BarDescription")]
    Bar,
}

What I get:

{"FooBar":0}

I'd like to get one of the following (preferably the first, but either one works):

{"FooBar": "FooValue"}
{"FooBar": "Foo"}
1
  • Hey ! were you able to solve the problem using the approach suggested below ? If not can you please update details and possibly resolution ? If yes can you please upvote and/or mark response below as asnwer ? Commented Jul 31, 2017 at 7:59

1 Answer 1

0

You'll need to reference JSON.NET use StringEnumConverter attribute on your property as follows :

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public SomeEnum FooBar {get;set;}

Please refer to newtonsoft docs for more details Hope this helps !

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.