Search code examples
c#jsonjson-deserialization

JSON deserialize dictionaries with varying keys


I'd like to deserialize some JSON strings like this:

    {"time":1506174868,"pairs":{
    "AAA":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
    "AAX":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
    "AQA":{"books":8,"min":0.1,"max":1.0,"fee":0.01}
    }}

where AAA, AAX, ... there are hundreds of variations

I paste this Json as class in VS2017 and get the following:

public class Rootobject
{
    public int time { get; set; }
    public Pairs pairs { get; set; }
}

public class Pairs
{
    public AAA AAA { get; set; }
    public AAX AAX { get; set; }
    public AQA AQA { get; set; }
}

public class AAA
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

public class AAX
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

public class AQA
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

I'd try to avoid hundreds of class declarations since all classes are same except their name.

I tried to serialize this as array or list but I get exception since this is not an array.

I use Newtonsoft JSON lib.

Thank you


Solution

  • Sure, you can parse the json string to object as follows:

        public class Rootobject
    {
        public int time { get; set; }
        public Dictionary<string, ChildObject> pairs { get; set; }
    }
    
    public class ChildObject
    {
    
        public int books { get; set; }
        public float min { get; set; }
        public float max { get; set; }
        public float fee { get; set; }
    }
    
    class Program
    {
        static string json = @"
            {""time"":1506174868,""pairs"":{
            ""AAA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
            ""AAX"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
            ""AQA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01}
            }
        }";
    
        static void Main(string[] args)
        {
            Rootobject root = JsonConvert.DeserializeObject<Rootobject>(json);
            foreach(var child in root.pairs)
            {
                Console.WriteLine(string.Format("Key: {0}, books:{1},min:{2},max:{3},fee:{4}", 
                    child.Key, child.Value.books, child.Value.max, child.Value.min, child.Value.fee));
            }
    
        }