You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Unity C#中解析Express发送的多个JSON对象

解决Unity解析Express发送的多对象JSON问题

问题根源

你的C#序列化类结构和服务器返回的JSON格式完全不匹配,同时解析时的额外包装逻辑错误,导致解析失败或字段为空。另外服务器端错误使用toString()导致数据损坏。

正确的C#序列化类定义

根据服务器返回的JSON结构,需要定义与字段一一对应的类:

[System.Serializable]
public class AccountData
{
    public string _id;
    public string username;
    public string password;
    public string email;
    public int hhs;
    public int level;
    public int xp;
    public int currency;
    public int premiumCurrency;
    public int __v;
}

[System.Serializable]
public class ScoreData
{
    public string _id;
    public string username;
    public int score;
    public int __v;
}

[System.Serializable]
public class ServerResponse
{
    public AccountData[] account;
    public ScoreData[] score;
}

正确的解析代码

服务器返回的JSON本身就是一个完整的根对象,不需要额外包装,直接解析即可:

// jsonText是UnityWebRequest接收到的原始JSON字符串
ServerResponse response = JsonUtility.FromJson<ServerResponse>(jsonText);

// 访问数据示例
if (response.account != null && response.account.Length > 0)
{
    Debug.Log("用户名:" + response.account[0].username);
}
if (response.score != null && response.score.Length > 0)
{
    Debug.Log("分数:" + response.score[0].score);
}

服务器端代码修正

不要对accountData和scoreData调用toString(),Mongoose查询返回的结果(文档数组)会被Express自动序列化为正确的JSON格式,恢复原来的代码即可:

res.send({account: accountData, score: scoreData});

错误原因说明

  1. 你之前定义的DataPackage类用string类型对应JSON中的对象数组,类型不匹配,导致解析后字段为空。
  2. 解析时额外包装{"dataPackages":...}或数组结构,完全偏离了服务器返回的JSON层级,导致解析失败。
  3. 服务器端调用toString()会把对象转为[object Object]字符串,破坏了JSON结构,无法被正确解析。

内容的提问来源于stack exchange,提问作者Joshua Simpson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:48:20