I have a program that needs to recieve a JSON object, which contains an object with a list of objects and an object inside each object in the list.
Theres no problem accessing the objects inside the "OuterGameResponse", but the Usernames are Null. I access the Highscores lige this:
string json = @"{""Games"":[{""Highscore"":35,""Coinsgained"":35,""Starttime"":""2021-12-08T12:30:50.543766"",""User"":{""Username"":""Smorgaard""}},{""Highscore"":35,""Coinsgained"":0,""Starttime"":""2021-12-08T13:09:00.384853"",""User"":{""Username"":""Smorgaard""}},{""Highscore"":25,""Coinsgained"":25,""Starttime"":""2021-12-08T11:14:16.125606"",""User"":{""Username"":""Smorgaard""}},{""Highscore"":10,""Coinsgained"":10,""Starttime"":""2021-12-08T12:49:28.987071"",""User"":{""Username"":""Smorgaard""}},{""Highscore"":0,""Coinsgained"":0,""Starttime"":""2021-12-08T12:48:57.309838"",""User"":{""Username"":""Smorgaard""}}],""Message"":""OK"",""Code"":200}";
GamesResponse _gr = JsonConvert.DeserializeObject<GamesResponse>(json);
Console.WriteLine(_gr.Games[0].Highscore);
But can't do something like this:
Console.WriteLine(_gr.Games[0].User.Username);
Is there any way to do this, without the objects inside the list being nulls?
Below is the classes i want to deserialize the JSON into.
[Serializable]
public class GamesResponse
{
public List<OuterGamesResponse> Games;
public string Message;
public int Code;
}
[Serializable]
public class OuterGamesResponse
{
public int Coinsgained;
public int Highscore;
public DateTime Starttime;
public InnerGamesResponse User;
}
[Serializable]
public class InnerGamesResponse
{
public string Username;
}
CodePudding user response:
Is there any way to do this
At the risk that you're not actually using Newtonsoft, and you've just stuck the first two lines in as a test harness for our benefit, but are instead using e.g. System.Text.Json (perhaps implicitly via some ReadAsJsonAsync web extension call) with its default settings you should note that we typically make our classes that we de/ser using properties, rather than fields, so like:
public class GamesResponse
{
public List<OuterGamesResponse> Games {get;set;}
public string Message {get;set;}
public int Code {get;set;}
}
The {get;set;}
is the minimum code necessary to turn a field into a property.
Newtonsoft isn't as fussy, and will de/ser properties or fields, but System.Text.Json for example, will not de/ser fields unless it's a recent version and the fields have been marked with [JsonInclude]
or you've specified that they should be included in the serializer options
CodePudding user response:
In the actual code i recieve the JSON data via Websocketshap as shown below - could the problem occur here in any way?
private GamesResponse _gr;
public LeaderboardManager()
{
WebSocketClient.OnMessageEvent = this.OnMessage;
}
void OnMessage(object sender, MessageEventArgs e)
{
_dataRecieved = true;
_gr = JsonConvert.DeserializeObject<GamesResponse>e.Data);
}