Newtonsoft.Json 序列化键值自动小写

使用 Discord Webhook 时发现属性的键值需要严格按照文档规定的小写才能被读取,而我的类是这样的

public class PostContent {
    public string Content { get; set; }
    public List<Embed> Embeds { get; set; } = new List<Embed>();
}

如果直接使用 Json.NET(Newtonsoft.Json)序列化

var json = JsonConvert.SerializeObject(message, Formatting.Indented);

结果会是这样的

{
  "Content": "New Free Game(s)",
  "Embeds": [
    {
      "Title": "Test 1",
      "Url": "https://store.steampowered.com",
      "Description": "This is a new free game",
      "Footer": null
    },
    {
      "Title": "Test 2",
      "Url": "https://store.steampowered.com",
      "Description": "This is another new free game",
      "Footer": {
        "Text": "From https://github.com/azhuge233/SteamDB-FreeGames-dotnet"
      }
    }
  ]
}

每个属性的键值都跟随了类内成员的命名

如果要在序列化时自动小写键值名称,可以手动设定 JsonSerializerSettings

var jsonLowercaseBySettings = JsonConvert.SerializeObject(message, new JsonSerializerSettings { 
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Formatting = Formatting.Indented
});

结果就会变成这样

{
  "content": "New Free Game(s)",
  "embeds": [
    {
      "title": "Test 1",
      "url": "https://store.steampowered.com",
      "description": "This is a new free game",
      "footer": null
    },
    {
      "title": "Test 2",
      "url": "https://store.steampowered.com",
      "description": "This is another new free game",
      "footer": {
        "text": "From https://github.com/azhuge233/SteamDB-FreeGames-dotnet"
      }
    }
  ]
}

也可以直接在类内使用标注

public class PostContent {
    [JsonProperty("content")]
    public string Content { get; set; }
    [JsonProperty("embeds")]
    public List<Embed> Embeds { get; set; } = new List<Embed>();
}

使用标注后,即使不指定 JsonSerializerSettings,结果也会变成这样

{
  "content": "New Free Game(s)",
  "embeds": [
    {
      "title": "Test 1",
      "url": "https://store.steampowered.com",
      "description": "This is a new free game",
      "footer": null
    },
    {
      "title": "Test 2",
      "url": "https://store.steampowered.com",
      "description": "This is another new free game",
      "footer": {
        "text": "From https://github.com/azhuge233/SteamDB-FreeGames-dotnet"
      }
    }
  ]
}

使用标注可以将对应键值改为任何指定名称,而指定 JsonSerializerSettings 只会更改大小写

发表回复

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据