.netjson-deserializationjsonserializer

JsonSerializer deserialize custom JSON


I have a json-file that has the following format:

{"0":{"Height":190,"Left":1640,"Top":170,"Width":600},"1":{"Height":52,"Left":2250,"Top":306,"Width":112},"10":{"Height":38,"Left":2011,"Top":794,"Width":378},"100":{"Height":45,"Left":192,"Top":3318,"Width":131},"101":{"Height":42,"Left":1211,"Top":3367,"Width":1216}}

The special case in this json-file:

I have a class Geometry that looks like the following:

public class Geometry
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Left { get; set; }
    public int Top { get; set; }
}

Is it possible to parse the json-file by ignoring the "enumeration" "1", "2", "3", and so on and just considers the content of each such node (that translates to class Geometry)? As output I want an object List<Geometry>.

How can I achieve this?


Solution

  • What the JSON represents is effectively a Dictionary<string, Geometry> - or if you're happy for the keys to be parsed, a Dictionary<int, Geometry>. I'd suggest parsing it as that, and then constructing a list from the result. If you don't care about the keys or the order at all, I'd just use:

    var list = JsonConvert.DeserializeObject<Dictionary<string, Geometry>>()
        .Values
        .ToList();
    

    If you want to use the value of the keys for ordering, you could write:

    var list = JsonConvert.DeserializeObject<Dictionary<int, Geometry>>()
        .OrderBy(pair => pair.Key)
        .Values
        .ToList();
    

    (I'd expect broadly the same code to work for all JSON libraries.)