Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

deserialize json to object with a dictionary System.Text.Json

I am working on a .Net 6.0 project, and I want to migrate from Newtonsoft.Json to System.Text.Json. So far most is working, except the following:

I’ve got this 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."
      }
   }
]

Which I am trying to store into the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

When I am deserializing using Newtonsoft.JSON, the dictionary gets populated just fine with the values from LocalizedValue

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

but when I try to use System.Text.Json, the dictionary stays empty

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

How can I use System.Text.Json and populate the dictionary?

>Solution :

The System.Text.Json library doesn’t deserialize to fields. If you change your class to use a property instead, your sample JSON will deserialize as expected.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading