Reputation: 4885
I am having trouble in deserializing the following JSON structure. Each node contains a ID and multiple language code with values. The number of language attributes is not consistent. But I need those values as a list of objects which has a Language field and a Value field.
[{
"id":"w_312457",
"eng":"deep-fat frying",
"ger":"Frittieren"
},
{
"id":"w_312458",
"fre":"frying",
"ger":"braten (in Öl)"
},
{
"id":"w_312477",
"ger":"perfekt gewürzte und abgestimmte Soße "
}]
I tried using JsonPropertyName
attribute and I got the ID value. But for lang nodes, I dont know what name I can specify. Following is my CLR object,
public class Word
{
public string Id { get; set; } // This is working
// What can I specify here. I need a list of objects each with a lang code and value.
}
Upvotes: 1
Views: 1384
Reputation: 6957
Method 1:
One approach would be to simply adding all the values and checking if they exist. For example this is the class that contains all the language values:
public class Word
{
public string id { get; set; }
public string eng { get; set; }
public string ger { get; set; }
public string fre { get; set; }
}
And you get the list such as:
var words = JsonConvert.DeserializeObject<List<Word>>(json);
Of course this assumes there are only 3 languages and more will not be added (which never happens!)
Method 2:
As shown in this thread, you can deserialize to a list of dictionary objects like this:
var words = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
And you can access all keys and values like this:
foreach (var word in words)
{
foreach (var key in word.Keys)
{
Console.WriteLine($"value for the key {key} is {word[key]}");
}
}
This will produce the following result:
value for the key id is w_312457
value for the key eng is deep-fat frying
value for the key ger is Frittieren
value for the key id is w_312458
value for the key fre is frying
value for the key ger is braten (in Öl)
value for the key id is w_312477
value for the key ger is perfekt gewürzte und abgestimmte Soße
Upvotes: 2