【问题标题】:Parse Json Response to Multiple Objects C# unity解析对多个对象的 Json 响应 C# unity
【发布时间】:2020-06-24 18:04:36
【问题描述】:

我正在尝试构建多人游戏,其中 Java 是我的服务器,Unity 是我的 Clinet。 我能够将数据发送到服务器并在服务器(Java 服务器)中以 Json 格式读取数据但是当我尝试读取响应时,我遇到了问题。我无法正确地将 Json 响应映射到在 Unity 中创建的类。

请在下面找到。

public class Player
{
    public string playerID;
    public string name;
    public string playerPosX;
    public string playerPosY;
    public string playerPosZ;
}

public class Lobby 
{

    public string lobbyID;

    public ArrayList player;
}


lobby = JsonUtility.FromJson<Lobby>(response);
Debug.Log(lobby.lobbyID);
Debug.Log(lobby.player.Count);

我将 json 数据作为

{"player":[{"playerID":"P1","name":"","playerPosX":"","playerPosY":"","playerPosZ":"","myne":false}],
"lobbyID":"L1"
}

我收到以下错误。 在第二个日志 对象引用未设置为对象的实例

【问题讨论】:

    标签: c# json unity3d


    【解决方案1】:

    不确定您是否被锁定在使用 Unity Json 实用程序,但我使用 Newtonsoft.Json nuget 库成功处理了您的 Json 字符串:

    using Newtonsoft.Json;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string json = "{\"player\":[{\"playerID\":\"P1\",\"name\":\"\",\"playerPosX\":\"\",\"playerPosY\":\"\",\"playerPosZ\":\"\",\"myne\":false}],\"lobbyID\":\"L1\"}";
                Lobby lobby = JsonConvert.DeserializeObject<Lobby>(json);
                System.Diagnostics.Debug.WriteLine(lobby.lobbyID);
                System.Diagnostics.Debug.WriteLine(lobby.player.Length);
            }
        }
    
        public class Lobby
        {
            public Player[] player { get; set; }
            public string lobbyID { get; set; }
        }
    
        public class Player
        {
            public string playerID { get; set; }
            public string name { get; set; }
            public string playerPosX { get; set; }
            public string playerPosY { get; set; }
            public string playerPosZ { get; set; }
            public bool myne { get; set; }
        }
    }
    

    输出是:

    L1
    1
    

    我猜你在找什么。

    【讨论】:

    • 如果我使用 get 并设置它不起作用,即使 Lobby ID 为空
    • 我可以看到你使用 Newtonsoft.Json 有区别,但我使用 UnityEngine.JsonUtility
    • 感谢合作伙伴!添加了这些新库并开始工作。 Unity 中的默认 Json parcer 未按预期工作。
    【解决方案2】:

    这个结构应该可以工作,反序列化为 Lobby 类型:

    public class Player
    {
        public string playerID;
        public string name;
        public string playerPosX;
        public string playerPosY;
        public string playerPosZ;
        public bool myne;
    }
    
    public class Lobby
    {
        public List<Player> player;
        public string lobbyID;
    }
    

    【讨论】:

    • 不工作可能是我的 Json api 需要更改我猜
    • 是的 Newtonsoft.Json 是更好的库,速度更快,不那么严格,经过良好测试并支持 Microsoft。然后只需使用 JsonConvert 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多