Alexandru Alexandru - 1 year ago 121
C# Question

Deserializing this object in JSON.NET

I have the following object:

{
"pickups": {
"7": [
5,
8
],
"10": [
6,
7,
9
],
"15": [
1
],
"20": [
0,
2
],
"25": [
3,
4
]
}
}


I'd like to de-serialize each pickups element into the following object:

public class Pickups {
public Pickup[] pickups;
}

public class Pickup {
public int Group; // This could be the 7, 10, 15, 20, 25, etc.
public int[] Values; // If this was the "7" grouping, it would contain 5, 8.
}


As you can see from the data its a bit tricky to do this. I've been trying to use a JsonConverter to convert the object with a bit of custom code but its been a nightmare and I haven't been able to get it right. I am wondering if anyone would know the best way to convert this type of object into the correct format I need?

Answer Source

While a converter would be a good choice you can still deserialize the Json and construct the desired object graph

var root = JsonConvert.DeserializeObject<RootObject>(json);
var pickups = new Pickups {
    pickups = root.pickups.Select(kvp =>
        new Pickup {
            Group = int.Parse(kvp.Key),
            Values = kvp.Value
        }
    ).ToArray()
};

Where

public class RootObject {
    public IDictionary<string, int[]> pickups { get; set; }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download