Reputation: 123
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:
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?
Upvotes: 12
Views: 19425
Reputation: 61
JsonSerializerOptions
class has IncludeFields
property which can be used to deserialize to field variables
Upvotes: 3
Reputation: 31238
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();
}
Upvotes: 18