1

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.
 }
Jawahar
  • 4,775
  • 1
  • 24
  • 47
  • 2
    Have you made any inroads with any approaches yet? It sounds like you want a `List>`, then parse the dictionaries afterwards. – James Thorpe Sep 28 '15 at 14:15
  • 1
    I would be tempted to change the structure of your JSON slightly. So the definitions would be in any array: `"id": "w_313223", "translations": [ { "lang": "ger", "value": "perfekt gewürzte und abgestimmte Soße" } ]` do you see what I mean? That way the array can have `x` amount of translations in – Callum Linington Sep 28 '15 at 14:28

1 Answers1

2

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

Community
  • 1
  • 1
Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40