简体   繁体   English

我可以配置ServiceStack.Text来将枚举值序列化为camelCase吗?

[英]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和ServiceStack.Text以将POCO对象序列化为JSON。 JSON.NET seems incredibly flexible, but at a bit of a performance cost. JSON.NET似乎非常灵活,但性能成本有点高。 ServiceStack.Text seems to offer nearly everything I need with better performance. ServiceStack.Text似乎提供了几乎所有我需要的更好的性能。 There's really only one thing that ServiceStack appears to lack... ServiceStack似乎只缺少一件事......

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: 如果我使用以下代码使用camelCase将ServiceStack配置设置为序列化:

ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

I end up with the Status property serialized as follows: 我最终将Status属性序列化如下:

status : ActiveAgent status:ActiveAgent

Notice that the property name is camel case, but the enum value is PascalCase. 请注意,属性名称是camel case,但枚举值是PascalCase。

This behavior seems consistent whether I use ServiceStack.Text's JsonSerializer or TypeSerializer . 无论我使用ServiceStack.Text的JsonSerializer还是TypeSerializer这种行为似乎都是一致的。

Is there a simple way in ServiceStack to change this behavior so that the value is also camelCase? ServiceStack中是否有一种简单的方法可以更改此行为,以便值也是camelCase?

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. 不,该值是JSON和JSV序列化程序中的字符串文字,并且序列化程序中没有选项可以更改实际值以使用camelCase或任何其他修饰符。

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. 唯一的方法是在没有实际重命名枚举的情况下使用camelCase值来为枚举指定自定义序列化函数。 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. 默认情况下,ServiceStack.Text不会为自定义序列化fn发出默认值,因此您要么添加PersonStatus.None值(不会发出),要么设置JsConfig.IncludeNullValues = true以使ServiceStack.Text发出默认值值。

All together this will look like: 这一切看起来像:

JsConfig.EmitCamelCaseNames = true;
JsConfig.IncludeNullValues = true;
JsConfig<PersonStatus>.SerializeFn = text => text.ToString().ToCamelCase();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM