Reputation: 14141
I am using Unity and Gamesparks. I am getting a Gamesparks object return but I am unable to access the data inside using C#.
private void OnScriptMessage(ScriptMessage message)
{
switch (message.ExtCode)
{
case "EndTurnMessage":
{
var data = message.Data;
string playerID = data.GetString("playerID");
print(message.JSONString);
break;
}
print(message.JSONString);
displays
{"@class":".ScriptMessage","data":{"player":{"status":"win","choice":"scissors","newScore":1},"opponent":{"status":"lost","choice":"paper","newScore":0}},"extCode":"roundWonMessage","messageId":"5c74b1a8bcb1b604f0275ed5","notification":true,"playerId":"5c5b5823642c55481643846d","summary":"ScriptMessage"}
UnityEngine.MonoBehaviour:print(Object)
I wish to get newScore
etc but I am confused with C# JSON
Upvotes: 1
Views: 927
Reputation: 12243
Your data is as follows:
"@class":".ScriptMessage","data":{"player":{"status":"win","choice":"scissors","newScore":1},"opponent":{"status":"lost","choice":"paper","newScore":0}},"extCode":"roundWonMessage","messageId":"5c74b1a8bcb1b604f0275ed5","notification":true,"playerId":"5c5b5823642c55481643846d","summary":"ScriptMessage"}
You need to deserialize it using -> JsonUtility.FromJsonOverwrite(json, @class);
But to just get that one value you'd probably just need a good way of parsing your JSON. Under the base JSON root node is data, playerId, extCode, messageId, notification, summary. You need to treat the field "data" as a JSONObject and then both "player" and "opponent" as JSON Objects. Parse the value within it for newScore.
So your code would look something like this (this is to be used as a general guideline):
var data = message.Data;
string playerID = data.GetString("playerID");
var _data = data.GetObject("data"); //whatever to get data as JSON or Object
var _player = _data.GetObject("player"); //whatever to get data as JSON or Object
var _opponent= _data.GetObject("opponent"); //whatever to get data as JSON or Object
int _mscorePlayer = _player.GetInteger("newScore"); //Whatever the getter is for JSON Number it could be GetNumber or something comparable.
int _mscoreOpponent= _opponent.GetInteger("newScore"); //Whatever the getter is for JSON Number it could be GetNumber or something comparable.
print(message.JSONString);
print("your playerId:\t" + playerId);
print("your newScore:\t" + _mscorePlayer);
print("opponent newScore:\t" + _mscoreOpponent);
break;
Upvotes: 1