Reputation: 23
I'm attempting to parse a rather convoluted/unnecessarily complicated JSON output using newtonsoft in C# however for some reason my parser always returns null. I have searched all over SO and cant't seem to find a solution.
An example of a JSON file I'm trying to parse:
{
"success": 1,
"d": {
"gameData": {
"MJ2Y7tDg": {
"scores": [
{
"max": 1.83,
"avg": 1.73,
"rest": 2,
"active": true,
"scoreid": "2c556xv464x0x4vtqc"
},
{
"max": 3.47,
"avg": 3.24,
"rest": 2,
"active": true,
"scoreid": "2c556xv498x0x0"
},
{
"max": 6.06,
"avg": 5.08,
"rest": 1,
"active": true,
"scoreid": "2c556xv464x0x4vtqd"
}
],
"count": 62,
"highlight": [
false,
true
]
},
"jZICYUQu": {
"scores": [
{
"max": 2.25,
"avg": 2.13,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuiv"
},
{
"max": 3.55,
"avg": 3.29,
"rest": null,
"active": true,
"scoreid": "2c5guxv498x0x0"
},
{
"max": 3.9,
"avg": 3.33,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuj0"
}
],
"count": 62,
"highlight": [
false,
false
]
}
}
}
}
This is what i have so far, I am very new to JSON wrangling :)
public class RootObject
{
public int success { get; set; }
public List<d> d { get; set; }
}
public class d
{
public List<gameData> gameData { get; set; }
}
public class gameData
{
public IDictionary<string, Score> gameData{ get; set; }
public List<scores[]> GameList;
}
public class Score
{
public double max { get; set; }
public double avg { get; set; }
public int rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
Anyone with more JSON wrangling experience know how to get this working?
Thankyou in advanced. P.S I am currently in high school, learning C#
Upvotes: 1
Views: 2411
Reputation: 8498
The parser returns null because structure of your classes doesn't correctly resemble the structure of JSON. The correct structure of classes would be:
public class RootObject
{
public int success { get; set; }
public Class_d d { get; set; }
}
public class Class_d
{
public Dictionary<string, GameData> gameData { get; set; }
}
public class GameData
{
public List<Score> scores { get; set; }
public int count { get; set; }
public bool[] highlight { get; set; }
}
public class Score
{
public decimal max { get; set; }
public decimal avg { get; set; }
public int? rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
and you can use it as follows:
string json = "..."; // the JSON in your example
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
Upvotes: 3