Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I configure ServiceStack.Text to serialize enum values to camelCase?

I'm looking at both JSON.NET and ServiceStack.Text to serialize POCO objects to JSON. JSON.NET seems incredibly flexible, but at a bit of a performance cost. ServiceStack.Text seems to offer nearly everything I need with better performance. There's really only one thing that ServiceStack appears to lack...

If I have an object that contains an enum property, say an enum like the following...

public enum PersonStatus
    {
        ActiveAgent,
        InactiveAgent
    }

public class Person
    {
        //A bunch of other properties
        public PersonStatus Status { get; set; }
    }

If I set the ServiceStack config to serialize using camelCase using the following code:

ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

I end up with the Status property serialized as follows:

status : ActiveAgent

Notice that the property name is camel case, but the enum value is PascalCase.

This behavior seems consistent whether I use ServiceStack.Text's JsonSerializer or TypeSerializer.

Is there a simple way in ServiceStack to change this behavior so that the value is also camelCase?

like image 842
Steve Brouillard Avatar asked Dec 16 '22 03:12

Steve Brouillard


1 Answers

No, the value is a string literal in both the JSON and JSV serializers and there's no option in the serializer that will change actual value to use camelCase or any other modifer.

The only way to do this is without actually renaming the enum to have camelCase values is to specify a custom serialize function for the enum. By default ServiceStack.Text doesn't emit default values for custom serialize fn's so you either want to add in a PersonStatus.None value (which won't be emitted) or set JsConfig.IncludeNullValues = true to get ServiceStack.Text to emit default values.

All together this will look like:

JsConfig.EmitCamelCaseNames = true;
JsConfig.IncludeNullValues = true;
JsConfig<PersonStatus>.SerializeFn = text => text.ToString().ToCamelCase();
like image 118
mythz Avatar answered Dec 18 '22 18:12

mythz