Parse JSON string with inconsistent field names

后端 未结 1 754
梦如初夏
梦如初夏 2021-01-24 11:49

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 consi

相关标签:
1条回答
  • 2021-01-24 12:27

    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

    0 讨论(0)
提交回复
热议问题