.NET Core json 动态属性序列化 (ExpandoObject) [英] .NET Core json serialization of properties on dynamic (ExpandoObject)

查看:49
本文介绍了.NET Core json 动态属性序列化 (ExpandoObject)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .NET Core 1.0 中有一个 web api,我喜欢属性默认序列化为 camelCasing 而不是 PascalCasing 的新功能.

I have a web api in .NET Core 1.0 and I like the new feature that properties are by default serialized to camelCasing instead of PascalCasing.

但是,我的一些 api 方法返回 dynamicExpandoObject 并且它们的属性按原样序列化,这意味着如果我将它们添加到动态对象中PascalCasing 那么它们将被序列化.

However, some of my api methods are returning dynamic or ExpandoObject and the properties on those are serialized as they are, meaning if I add them to the dynamic object as PascalCasing then that's how they will be serialized.

我认为这是因为动态对象与 Dictionary 密切相关,这就是它表现不同的原因.

I figure it's because a dynamic object is closely related to Dictionary<string, object> and that's why it is behaving differently.

如何使用 camelCasing 以一种好的方式使 dynamic 序列化?

How can I make the dynamic be serialized with camelCasing in a nice way?

(我可以通过在从 API 返回它们之前使用小写键在每个返回的动态中重新创建字典来实现,但我正在寻找一种非常好的方法来实现目标)

(I could do it by re-creating the dictionary in every returned dynamic with a lowercase key just before returning them from the API, but I am looking for a quite nice way to accomplish the goal)

推荐答案

这可以在 Startup.cs -> ConfigureServices 中解决:

This can be solved with this in Startup.cs -> ConfigureServices:

services.AddMvc().AddJsonOptions(opt =>
{
    opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

在一些地方提到这是现在 ASP.NET Core 1.0 的默认行为,但实际上并非如此.添加此行会影响动态属性,默认情况下不影响这些属性.

It is mentioned a few places that this is now the default behavior for ASP.NET Core 1.0 but that is actually not true. Adding this line affects dynamic properties and those are not affected by default.

这篇关于.NET Core json 动态属性序列化 (ExpandoObject)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆