Search code examples
c#jsonconvert

C# JsonConvert - How to parse an irregular key / value JSON?


I'm trying to get a json with JsonConvert from a file that contains the following information:

 {
  "Programacion": {
    "F201604260700": { "Comercial": "COM63039" },
    "F201604260805": { "Comercial": "COM63039" },
    "F201604260944": { "Comercial": "COM63039" },
    "F201604261113": { "Comercial": "COM63039" }
    }
 }

To be able to store the json I have created a class called Tandas, because each "Programming" has a different key ("F201604260700", "F201604260805") I have not managed to create an array of data that works for me

public class Tandas
        {
            // Not work
            //public IEnumerable<IDictionary<string, string>> Programacion { get; set; }

            // Not work
            public List<KeyValuePair<string, KeyValuePair<string, string>>> Programacion { get; set; }
        }

I do not know much about fixes and objects in C #, what solution could I give?

// Error
this.tandas = JsonConvert.DeserializeObject<Tandas>(json_tandas_string);

Solution

  • JsonConvert can deserialize a JSON object to a Dictionary<string, T> where T is the type of the values.

    In this case, the values are also JSON objects, with string values, so T in this case would be Dictionary<string, string>.

    Full class:

    public class Tandas
    {
        public Dictionary<string, Dictionary<string, string>> Programacion { get; set; }
    }
    

    You've now clarified that the inner objects contain regular keys, so you can define a class for that:

    public class InnerThing
    {
        public string Comercial { get; set; }
    }
    
    public class Tandas
    {
        public Dictionary<string, InnerThing> Programacion { get; set; }
    }