3

The Problem

Let's say I have an enum representing something or other:

public enum ResultState
{
    Found,
    Deleted,
    NotFound
}

In my serialized json, I'd like these values to be serialized as "found", "gone" or "not_found" respectively. (Note: this is not camelCase, but rather a totally custom string!)

I'm using JSON.NET

The Story So Far

I've got everything working almost right - enums are globally converted to strings via the StringEnumConverter, however I can't for the life of me see how to achieve something similar to the above.

My initial thoughts were to apply the JsonProperty(...) attribute to the relevant enum values, however this doesn't seem to work!

Potential Solution?

The only way I can think of getting this work is to write my own JsonConverter inheriting from StringEnumConverter, but with some additional magic to handle a new JsonName attribute I'd create.

As you might imagine, I don't relish the idea of this.

I was wondering if you wonderful people could suggest a simpler alternative?

2
  • It is surprisingly easy to create a new converter subclass. You probably could have done it in the time it took you to ask this question :) Commented Apr 23, 2013 at 20:35
  • You're probably right, but I wanted a more declarative approach. Turns out that the EnumMemberAttribute was staring me in the face the whole time. facepalm Commented Apr 23, 2013 at 20:38

1 Answer 1

10

As it happens, I was overthinking the whole thing.

I made use of the EnumMember attribute from System.Runtime.Serialization, which worked great.

Here's my new enum for completeness:

public enum QueryResultState
{
    [EnumMember(Value="found")]
    Found,

    [EnumMember(Value="gone")]
    Deleted,

    [EnumMember(Value="not_found")]
    NotFound
}

Don't forget to include the StringEnumConverter when calling JsonConvert.Serialize(...), as JSON.NET serializes Enums to Integers by default:

JsonConvert.SerializeObject(someObjectWithAnEnum, new StringEnumConverter());
Sign up to request clarification or add additional context in comments.

5 Comments

I don't get how this works? I tried QueryResultState r = QueryResultState.Deleted; var r2 = JsonConvert.SerializeObject(new { a = r }); and got {"a":1}
In addition to the above, you still need to use the StringEnumConverter. Pass one in on the SerializeObject overload.
Any reason not to include this info in your answer?
It's in my original question - about halfway down.
Dan, There is nothing connecting EnumMember to StringEnumConverter in your answer. Think for future readers and complete your answer. until then -1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.