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

Unity解析.NET Minimal API返回JSON到对象失败问题排查

解决Unity解析.NET Minimal API响应Value字段为空的问题

一、先排查后端返回结构(优先方案)

你的.NET Minimal API返回的JSON被自动包装成带contentType、serializerSettings、statusCode、value的结构,是导致Unity解析失败的核心原因。直接让后端返回纯ShipmentID列表即可:

修正后端接口代码

确保接口直接返回去重后的列表,而非包装对象:

app.MapGet("/mytableDistinct", async (MyDbContext db) =>
{
    var distinctShipmentIds = await db.MyTable
        .Select(t => t.ShipmentID)
        .Distinct()
        .ToListAsync();
    return distinctShipmentIds; // 直接返回列表,不要用Results.Ok()之外的包装逻辑
});

此时后端返回的JSON是纯数组格式:

["SHIP001", "SHIP002", "SHIP003"]

Unity端直接解析string[]或对应的实体类即可。

二、后端无法修改时,Unity端适配包装结构

如果必须保留后端的包装返回,需调整Unity的解析逻辑,匹配完整响应结构:

1. 创建匹配响应的序列化类

Unity的JsonUtility对字段大小写敏感,且要求类标记[Serializable]:

using UnityEngine;

[Serializable]
public class ApiResponseWrapper
{
    // 字段名必须和JSON中完全一致(注意是小写value还是大写Value)
    public ShipmentIdList value;
}

[Serializable]
public class ShipmentIdList
{
    // 对应列表字段,根据实际JSON键名调整
    public string[] ShipmentIDs;
}

2. 调整解析流程

先解析外层包装对象,再提取内部的value字段:

// 假设responseJson是从接口获取的完整响应字符串
ApiResponseWrapper responseWrapper = JsonUtility.FromJson<ApiResponseWrapper>(responseJson);
ShipmentIdList result = responseWrapper.value;

// 验证结果
if (result != null && result.ShipmentIDs != null)
{
    foreach (string id in result.ShipmentIDs)
    {
        Debug.Log("ShipmentID: " + id);
    }
}

3. 常见排查点

  • 用Debug.Log(responseJson)打印完整响应,确认value字段的大小写和嵌套结构
  • 所有嵌套类必须加[Serializable],JsonUtility无法解析未标记的类
  • 如果ShipmentID是数字类型,将string[]改为对应类型(如int[])

三、备选:用Newtonsoft.Json替代JsonUtility

若JsonUtility限制过多,可通过Unity Package Manager安装com.unity.nuget.newtonsoft-json,它支持大小写不敏感和更灵活的解析:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// 方式1:解析完整包装类
var wrapper = JsonConvert.DeserializeObject<ApiResponseWrapper>(responseJson);
ShipmentIdList result = wrapper.value;

// 方式2:直接提取value字段,无需定义完整包装类
JObject jsonObj = JObject.Parse(responseJson);
ShipmentIdList result = jsonObj["value"].ToObject<ShipmentIdList>();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:02:16