1

I'm using the JSON.NET package to deserialize a JSON response to a C# class but the json is oddly formatted. They are sending back an array of items where each item's name property is set to be the ID (weird because as you can see below, the ID already appears in the body of the object as 'player_id'). Like this:

{
    "5131": {
        "player_id": 5131,
        "prop1": "val1",
        "prop2": null,
        "prop3": "val3"
    },
    "5132": {
        "player_id": 5132,
        "prop1": "val1",
        "prop2": null,
        "prop3": "val3"
    }
}

Normally you'd would have a name-value pair where the name is something standard like 'player' and you'd have the id as a property in object.

Is there a way to define a C# class around this that it will deserialize into what I need (just an array of items, no dynamically named id props). Thanks

2
  • 2
    You can use a Dictionary<string, PROPCLASS> with PROPCLASS as a new class defining your properties. Commented Sep 9, 2021 at 15:31
  • Does this answer your question? json deserialization to C# Commented Sep 9, 2021 at 19:04

1 Answer 1

3

Since each object has a player_id that matches the object key values, you don't need to worry about capturing the object keys. I'd just serialize it to a Dictionary first, and then just take the values from that dictionary.

var players = JsonConvert.DeserializeObject<Dictionary<string, Player>>(input).Values;
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh of course, so simple it went right over my head :) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.