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?

Dan
  • 998
  • 10
  • 21
  • 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 :) – Brandon Apr 23 '13 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* – Dan Apr 23 '13 at 20:38

1 Answers1

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());
Dan
  • 998
  • 10
  • 21
  • I don't get how this works? I tried `QueryResultState r = QueryResultState.Deleted; var r2 = JsonConvert.SerializeObject(new { a = r });` and got `{"a":1}` – I4V Apr 23 '13 at 20:44
  • In addition to the above, you still need to use the StringEnumConverter. Pass one in on the SerializeObject overload. – Dan Apr 23 '13 at 20:48
  • Any reason not to include this info in your answer? – I4V Apr 23 '13 at 20:51
  • It's in my original question - about halfway down. – Dan Apr 23 '13 at 20:54
  • Dan, There is nothing connecting `EnumMember` to `StringEnumConverter` in your answer. Think for future readers and complete your answer. until then `-1` – I4V Apr 23 '13 at 20:55