Reputation: 712
I have the following json:
{
"GameConfig":{
"TeamConstraint":{
"SameTeamPlayers":[
"Raghav",
"Surya"
],
"OppositeTeamPlayers":[
"Wolfman",
"Pawan"
]
},
"Players":[
"Tramp",
"Surya",
"Raghav",
"Krishna",
"Sanjay",
"Bala",
"Wolfman",
"Eagle",
"Sai",
"Pawan",
"Joo",
"Srikanth"
],
"Ranks":{
"Tramp":10,
"Surya":10,
"Raghav":8,
"Krishna":8,
"Eagle":8,
"Sai":8,
"Sanjay":7.5,
"Pawan":5,
"Wolfman":5.0,
"Srikanth":6,
"Bala":4.5,
"Joo":1.5
}
}
}
I am writing a simple console app .NET Core 3.1. I have tried both the JSON.NET as well as the new MSFT System.Text.Json deserializer. But I get only null values for all of the properties with the following Model object.
[Serializable]
public class GameConfig
{
public TeamConstraint TeamConstraint { get; set; }
public List<string> Players { get; set; }
public Dictionary<string, double> Ranks { get; set; }
}
[Serializable]
public class TeamConstraint
{
public List<string> OppositeTeamPlayers { get; set; }
public List<string> SameTeamPlayers { get; set; }
}
I have tried several additional options like using a contract resolver with CamelCase properties and changing the code and json accordingly but nothing has worked so far. What am I missing?
This is the code I am using to deserialize.
var jsonString = File.ReadAllText(TeamGeneratorStandardSettings.Default.GameConfigFile);
var gameConfig = JsonSerializer.Deserialize<GameConfig>(jsonString);
Upvotes: 0
Views: 1924
Reputation: 33833
You are trying to deserialize into GameConfig
, whereas that is simply a top-level property of your overall json object structure. You need a new top-level type to deserialize into that contains your GameConfig
object.
public class GameData
{
public GameConfig GameConfig { get; set; }
}
var jsonString = File.ReadAllText(TeamGeneratorStandardSettings.Default.GameConfigFile);
var gameConfig = JsonSerializer.Deserialize<GameData>(jsonString);
Alternatively, you could remove the wrapping object from your json and still deserialize directly to a GameConfig
object:
{
"TeamConstraint":{
"SameTeamPlayers":[
"Raghav",
"Surya"
],
"OppositeTeamPlayers":[
"Wolfman",
"Pawan"
]
},
"Players":[
"Tramp",
"Surya",
"Raghav",
"Krishna",
"Sanjay",
"Bala",
"Wolfman",
"Eagle",
"Sai",
"Pawan",
"Joo",
"Srikanth"
],
"Ranks":{
"Tramp":10,
"Surya":10,
"Raghav":8,
"Krishna":8,
"Eagle":8,
"Sai":8,
"Sanjay":7.5,
"Pawan":5,
"Wolfman":5.0,
"Srikanth":6,
"Bala":4.5,
"Joo":1.5
}
}
var jsonString = File.ReadAllText(TeamGeneratorStandardSettings.Default.GameConfigFile);
var gameConfig = JsonSerializer.Deserialize<GameConfig>(jsonString);
Upvotes: 4