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

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

问题描述

我在.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方法返回的是 dynamic ExpandoObject ,这些属性按原样进行序列化,这意味着如果我将它们作为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< string,object> 密切相关,这就是为什么它表现不同的原因。

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

我该如何制作 dynamic 是否可以通过 camelCasing 进行序列化?

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)

推荐答案

Th可以在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动态属性(ExpandoObject)的json序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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