【问题标题】:deserialize json to object with a dictionary System.Text.Json使用字典 System.Text.Json 将 json 反序列化为对象
【发布时间】:2021-11-22 13:31:20
【问题描述】:

我正在开发一个 .Net 6.0 项目,我想从 Newtonsoft.Json 迁移到 System.Text.Json。到目前为止,大多数都在工作,除了以下内容:

我有这个 json:

[
   {
      "Key":"ValidateRequired",
      "LocalizedValue":{
         "fr-FR":"Ce champ est obligatoire.",
         "en-GB":"This field is required.",
         "nl-BE":"Dit is een verplicht veld.",
         "de-DE":"Dieses Feld ist ein Pflichtfeld."
      }
   },
   {
      "Key":"ValidateEmail",
      "LocalizedValue":{
         "fr-FR":"Veuillez fournir une adresse électronique valide.",
         "en-GB":"Please enter a valid email address.",
         "nl-BE":"Vul hier een geldig e-mailadres in.",
         "de-DE":"Geben Sie bitte eine gültige E-Mail-Adresse ein."
      }
   },
   {
      "Key":"ValidateUrl",
      "LocalizedValue":{
         "fr-FR":"Veuillez fournir une adresse URL valide.",
         "en-GB":"Please enter a valid URL.",
         "nl-BE":"Vul hier een geldige URL in.",
         "de-DE":"Geben Sie bitte eine gültige URL ein."
      }
   }
]

我正在尝试将其存储到以下内容中:

public class Translations
{
    public string Key { get; set; }

    public Dictionary<string, string> LocalizedValue = new();
}

当我使用 Newtonsoft.JSON 进行反序列化时,字典会很好地填充来自 LocalizedValue 的值

jsonlocalization = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Translations>>(jsonString);

但是当我尝试使用 System.Text.Json 时,字典仍然是空的

jsonlocalization = System.Text.Json.JsonSerializer.Deserialize<List<Translations>>(jsonString);

如何使用 System.Text.Json 并填充字典?

【问题讨论】:

    标签: c# json.net system.text.json asp.net-core-6.0


    【解决方案1】:

    System.Text.Json 库不会反序列化为字段。如果您将类更改为使用属性,则示例 JSON 将按预期反序列化。

    public class Translations
    {
        public string Key { get; set; }
        public Dictionary<string, string> LocalizedValue { get; set; } = new();
    }
    

    【讨论】:

    • 我刚刚有了同样的认识,并且正在制作一个现场演示来演示 - 不妨现在把它留在这里:dotnetfiddle.net/WvOaze
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多