【问题标题】:Force System.Text.Json to deserialize in CamelCase强制 System.Text.Json 在 CamelCase 中反序列化
【发布时间】: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


【解决方案1】:

引用this answer,使用Newtonsoft.Json

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Dynamic;
    
var jsonString = "{\"Property1\":\"s\", \"PropertyCamel\":{\"PropertyNested\":\"g\"}, \"PPP\":[{\"NestedList\":\"1\"}]}";
                // won't work if I used json
                // var json = JsonConvert.DeserializeObject(jsonString);
                var interimObject = JsonConvert.DeserializeObject<ExpandoObject>(jsonString);
                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                var myJsonOutput = JsonConvert.SerializeObject(interimObject, jsonSerializerSettings);

【讨论】:

  • 感谢您的回答。我们正在尝试在代码库上放弃使用 Newtonsoft,但这肯定比当前循环遍历 json 对象的实现要好得多
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2020-06-23
相关资源
最近更新 更多