4

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

4

1 回答 1

3

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

public class Translations
{
    public string Key { get; set; }
    public Dictionary<string, string> LocalizedValue { get; set; } = new();
}
于 2021-11-22T13:39:04.617 回答