【发布时间】:2022-01-02 20:37:34
【问题描述】:
我正在尝试使用 System.Text.Json 从 PascalCase 字符串中使用 camelCase 约定构建 JsonElement(或类似的)。有没有办法强制执行这种行为?
var jsonString = "{\"Property1\":\"s\", \"PropertyCamel\":{\"PropertyNested\":\"g\"}, \"PPP\":[{\"NestedList\":\"1\"}]}";
var deserialized = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(jsonString,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
});
var serialized = System.Text.Json.JsonSerializer.Serialize(
deserialized,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
});
// deserialized outputs property names in PascalCase
我也尝试过反序列化 -> 序列化 -> 反序列化但没有成功。
有办法吗?
【问题讨论】:
-
将
PropertyNameCaseInsensitive设置为true并再次序列化。 -
@Beltway 它也不起作用。我相信,因为它是一个 JsonElement 对象,它不会在
JsonCamelCaseNamingPolicy上运行代码 -
你不能将它映射到一个瞬态对象吗?默认情况下,
System.Text.Json在从用 PascalCase 编写的速记 getter 序列化时应该使用 camelCase。
标签: c# asp.net asp.net-core