C
C#ā€¢2y ago
Halfbax

ā” JSON serialization fails

After the serialization RiotChampionWrapper.Champions is null. The problem might be that each item has a different name. How can I fix it?
public class RiotChampionWrapper
{
[JsonPropertyName("data")]
private List<RiotChampion> Champions { get; set; }
}

public class RiotChampion
{
[JsonPropertyName("id")]
public string Id { get; set; }

[JsonPropertyName("key")]
public string Key { get; set; }

[JsonPropertyName("name")]
public string Name { get; set; }
}
public class RiotChampionWrapper
{
[JsonPropertyName("data")]
private List<RiotChampion> Champions { get; set; }
}

public class RiotChampion
{
[JsonPropertyName("id")]
public string Id { get; set; }

[JsonPropertyName("key")]
public string Key { get; set; }

[JsonPropertyName("name")]
public string Name { get; set; }
}
RiotChampionWrapper? items = JsonSerializer.Deserialize<RiotChampionWrapper>(data);
RiotChampionWrapper? items = JsonSerializer.Deserialize<RiotChampionWrapper>(data);
{
"type": "champion",
"format": "standAloneComplex",
"version": "13.10.1",
"data": {
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox"
},
"Ahri": {
"id": "Ahri",
"key": "103",
"name": "Ahri"
}
}
}
{
"type": "champion",
"format": "standAloneComplex",
"version": "13.10.1",
"data": {
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox"
},
"Ahri": {
"id": "Ahri",
"key": "103",
"name": "Ahri"
}
}
}
6 Replies
undisputed world champions
data in your json is not an array, but an object with properties Aatrox and Ahri it should be something like this if you want an array instead:
{
"type": "champion",
"format": "standAloneComplex",
"version": "13.10.1",
"data": [
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox"
},
"Ahri": {
"id": "Ahri",
"key": "103",
"name": "Ahri"
}
]
}
{
"type": "champion",
"format": "standAloneComplex",
"version": "13.10.1",
"data": [
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox"
},
"Ahri": {
"id": "Ahri",
"key": "103",
"name": "Ahri"
}
]
}
(with square brackets [])
Halfbax
HalfbaxOPā€¢2y ago
Sadly I am unable to change the json.
undisputed world champions
or your class could have a property private Dictionary<string, RiotChampion> Champions { get; set; } instead
Halfbax
HalfbaxOPā€¢2y ago
Thanks. That's works šŸ™‚
TheRanger
TheRangerā€¢2y ago
shouldn't it be public tho?
Accord
Accordā€¢2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?