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
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!
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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With