Alexandru
Alexandru

Reputation: 12932

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?

Upvotes: 1

Views: 112

Answers (3)

michivo
michivo

Reputation: 99

If it is a viable option for you to use JObject.Parse(...) instead, you could use the following code (and write it more cleanly, with exception handling and safe casts and so on):

var jsonPickups = JObject.Parse(json);
var myPickups = new Pickups
{
    pickups = jsonPickups.First.First.Select(x =>
    {
        JProperty xProp = x as JProperty;
        return new Pickup
        {
            Group = int.Parse(xProp.Name),
            Values = (xProp.Value as JArray).Select(y => int.Parse(y.ToString())).ToArray()
        };
    }).ToArray()
};

Upvotes: 0

krmzcn
krmzcn

Reputation: 1

This is what son2csharp.com says, its gets error because you can not define names with starting number.

public class Pickups
{
    public List<int> __invalid_name__7 { get; set; }
    public List<int> __invalid_name__10 { get; set; }
    public List<int> __invalid_name__15 { get; set; }
    public List<int> __invalid_name__20 { get; set; }
    public List<int> __invalid_name__25 { get; set; }
}

public class RootObject
{
    public Pickups pickups { get; set; }
}

But I think

[DataMember(Name = "Name")]

should work cause its not an error in JSON format side.

Upvotes: 0

Nkosi
Nkosi

Reputation: 247591

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; }
}

Upvotes: 6

Related Questions