[英]Parse Json Response to Multiple Objects C# unity
我正在尝试构建多人游戏,其中 Java 是我的服务器,Unity 是我的 Clinet。 我能够将数据发送到服务器并在服务器(Java 服务器)中以 Json 格式读取数据但是当我尝试读取响应时,我遇到了问题。 我无法正确 map 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"
}
我收到以下错误。 在第二个日志 Object 引用未设置为 object 的实例
Not sure if you're locked into using the Unity Json utility, but I had success with your Json string using the Newtonsoft.Json nuget library:
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; }
}
}
Output 是:
L1
1
这就是我收集的你正在寻找的东西。
这个结构应该可以工作,反序列化为 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.