使用字典将 JSON 反序列化为对象 System.Text.Json

10

我正在开发一个.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并填充字典?

1个回答

15
System.Text.Json 库无法反序列化到字段。如果您将类更改为使用属性,您的示例 JSON 将按预期反序列化。
public class Translations
{
    public string Key { get; set; }
    public Dictionary<string, string> LocalizedValue { get; set; } = new();
}

2
我刚刚意识到了同样的问题,并正在制作一个实时演示来展示 - 现在可以在这里留下链接:https://dotnetfiddle.net/WvOaze - Jamiec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接