Reputation: 931
i'm try to deserialize json, the result is work, but when serialize it became null, can you guys tell me where is wrong ?
My Result JSON:
{
"status": true,
"hostname": "139.99.32.82",
"port": 25565,
"protocol": "tcp",
"ping": 499,
"players": {
"online": 1,
"max": 1000
},
"cached": false
}
My Code :
var request = (WebRequest)WebRequest.Create("https://use.gameapis.net/mc/query/players/139.99.32.82");
request.Method = "GET";
var response = (WebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = reader.ReadToEnd();
reader.Close();
var serverstats = JsonConvert.DeserializeObject<ServerStats>(result);
var players = serverstats.players;
serveronline.Text = "Online Players: " + players[0].ToString();
My Server Class:
[JsonObject(MemberSerialization.OptIn)]
public class ServerStats
{
[JsonProperty]
public bool status { get; }
[JsonProperty]
public string hostname { get; set; }
[JsonProperty]
public List<OnlinePlayer> players { get; }
}
[JsonObject(MemberSerialization.OptIn)]
public class OnlinePlayer
{
[JsonProperty]
public int online { get;}
[JsonProperty]
public int max { get; }
}
Upvotes: 1
Views: 40
Reputation: 100545
You are trying to serialize object {"online": 1,"max": 1000}
into an array. If JSON you've shown is the right one you need single r/w element as players
:
public class ServerStats
{
public bool status { get; set;}
public string hostname { get; set; }
public OnlinePlayer players { get;set;} // Single item with set.
}
public class OnlinePlayer
{
public int online { get;set; }
public int max { get; set; }
}
Side note: make sure all necessary property are set-able.
Upvotes: 1