c# - ServiceStack JSON 在 dotnet 核心上序列化为小写?

标签 c# serialization servicestack .net-core servicestack-text

我正在使用 ServiceStack 运行 REST API,但在序列化响应对象时遇到了问题。更具体地说,当我在响应对象上调用 JsonSerializer.SerializeToString(.) 时,所有属性名称都以小写形式序列化。我试过摆弄 JsConfig.EmitCamelCaseNames 之类的参数,但这没有帮助。有任何想法吗?

请参阅下面的 ServiceStack 版本信息和屏幕截图。

"ServiceStack.Core": "1.0.32",
"ServiceStack.Kestrel": "1.0.32",

要序列化的响应对象: Object Definition

序列化字符串: Serialized String

我认为这是 dotnet core 特有的,因为这最初是我已迁移到 dotnet core 的 .NET 应用程序。我在以前的应用程序版本中从未见过这个问题。我知道我可以使用 native 序列化程序,但我认为 ServiceStack 更快(如果我错了请告诉我)。

最佳答案

此行为是 documented in the .NET Core Release Notes :

In addition to running flawlessly on .NET Core we’re also actively striving to find how we can best integrate with and leverage the surrounding .NET Core ecosystem and have made several changes to that end:

CamelCase

The JSON and JSV Text serializers are following .NET Core’s default convention to use camelCase properties by default. This can be reverted back to PascalCase with:

SetConfig(new HostConfig { UseCamelCase = false })

We also agree with this default, .NET Core seems to be centered around embracing the surrounding developer ecosystem where .NET’s default PascalCase protrudes in a sea of camelCase and snake_case JSON APIs. This won’t have an impact on .NET Service Clients or Text Serialization which supports case-insensitive properties, however Ajax and JS clients will need to be updated to use matching properties. You can use ss-utils normalize() methods to help with handling both conventions by recursively normalizing and converting all properties to lowercase.

自定义即席 JSON 序列化

以上将为您的 ServiceStack 服务使用 CamelCase,如果您只需要将一个临时对象序列化为 JSON,您可以将其包装在一个配置对象中以覆盖全局设置,例如:

using (JsConfig.With(new Config { TextCase = TextCase.PascalCase }))
{
    var json = results.ToJson();
}

关于c# - ServiceStack JSON 在 dotnet 核心上序列化为小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44815308/

相关文章:

c# - 启动具有访问器的事件

c# - Msbuild 使用唯一文件名复制和展平

c# - Vista/Windows 7 中字幕的透明度

c# - 我的项目不使用 NHibernate 是不是很愚蠢?

java - 反序列化对象是否保留静态值?

java - 当我有一个黑匣子要转换为字节数组或从字节数组转换时,如何在 Java 中进行序列化和反序列化?

PrintService 属性的 Java 序列化

oauth-2.0 - ServiceStack 中的 OAuth2 授权实现

web - 如何评估 Web 服务框架

http - Servicestack 请求 header 不包含 cookie