.NET Core json serialization of properties on dyna

2019-02-28 10:08发布

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.

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.

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

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

(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)

1条回答
beautiful°
2楼-- · 2019-02-28 10:39

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

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

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.

查看更多
登录 后发表回答