我以json的身份从Web服务器获取数据,但我无法反序列化它们并访问键(例如first_name)
信息在客户端中接收,但遗憾的是,此代码不会在Unity控制台中打印任何内容
我的代码:
socket.On("UserList", response =>
{
var result = JsonConvert.DeserializeObject<List<UserClass>>(response.ToString());
var first_name = result[0].first_name;
print(first_name);
});
用户类别:
public class UserClass
{
public string _id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string mobile { get; set; }
public string email { get; set; }
public DateTime createdAt { get; set; }
public DateTime updateAt { get; set; }
public int __v { get; set; }
}
在客户端接收的Json:
[
{
"_id": "83ca7d56cbc2b281wd4ee658",
"first_name": "sara",
"last_name": "Paulson",
"mobile": "09323456789",
"email": "sara@gmail.com",
"createdAt": "2023-01-20T12:46:38.384Z",
"updateAt": "2023-01-20T12:46:38.384Z",
"__v": 0
},
{
"_id": "59e41dku510239e83ed7e10m",
"first_name": "Evan",
"last_name": "Peters",
"mobile": "09327931248",
"email": "Evan@gmail.com",
"createdAt": "2023-02-10T10:35:26.687Z",
"updateAt": "2023-02-10T10:35:26.687Z",
"__v": 0
},
{
"_id": "64lm96c57a8a4f289fw0gg66",
"first_name": "Emma",
"last_name": "Roberts",
"mobile": "09325354769",
"email": "Emma@gmail.com",
"createdAt": "2023-01-20T13:11:46.402Z",
"updateAt": "2023-01-20T13:11:46.402Z",
"__v": 0
}
]
如何在Unity中访问此Json的密钥?
2条答案
按热度按时间k10s72fa1#
我检查了一下,发现即使是在JSON中指定数组也可以工作:
两种方式给予输出相同。https://dotnetfiddle.net/g2Dn1n
我做的唯一附加的事情是检查返回值。您应该在Unity中使用
Debug.Log()
来打印反序列化后获得的实际值。rekjcdws2#
经过几天的努力,答案终于找到了
为了解决这个问题,我对代码进行了如下编辑:
我的代码:
//输出:sara
用户类别:
在客户端接收的Json:
这样,您就可以访问从服务器发送的json值