Unity访问JSON对象

时间:2019-02-26 03:40:22

标签: c# json object unity3d

我正在使用Unity和Gamesparks。我得到一个Gamesparks对象返回,但是我无法使用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);显示

{"@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)

我希望得到newScore等,但是我对C#JSON感到困惑

1 个答案:

答案 0 :(得分:1)

您的数据如下:

"@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"}

您需要使用->反序列化 JsonUtility.FromJsonOverwrite(json,@class);

但是要获得一个值,您可能只需要一种解析JSON的好方法。在基本JSON根节点下是data,playerId,extCode,messageId,通知,摘要。您需要将字段“数据”视为JSONObject,然后将“玩家”和“对手”都视为JSON对象。解析其中的值  newScore。

您的数据如下:enter image description here

因此您的代码应如下所示(这将用作一般指导原则):

                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;