System.Text.Json不会将dynamic属性的属性进行Camelize

7xllpg7q  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(133)

我使用的是ASP.NET Core和System.Text.Json
下面是我的示例操作方法:

[HttpGet]
    public object Person()
    {
        dynamic relatedItems = new ExpandoObject();
        relatedItems.LastName = "Last";
        var result = new 
        {
            FirstName = "First",
            RelatedItems = relatedItems
        };
        return result;
    }

字符串
我得到的回应是

{
    firstName: "First",
    relatedItems: {
        LastName: "Last"
    }
}


如您所见,LastName是dynamic属性的一个属性,它没有 Camel 化。
我怎样才能使一切都回到 Camel 的情况下?

更新,这个答案不是我的答案。正如你所看到的,我已经正确地camelized了firstName属性。

ht4b089n

ht4b089n1#

ExpandoObject将被视为字典,所以除了PropertyNamingPolicy之外,还需要设置DictionaryKeyPolicy

dynamic relatedItems = new ExpandoObject();
relatedItems.LastName = "Last";
var result = new 
{
    FirstName = "First",
    RelatedItems = relatedItems
};
var s = JsonSerializer.Serialize(result, new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
});
Console.WriteLine(s); // prints {"firstName":"First","relatedItems":{"lastName":"Last"}}

字符串

相关问题