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

Unity反序列化含内部数组的API JSON数组时对象属性全部为空问题求助

解决Unity JsonUtility反序列化数组为自定义对象全属性为null的问题

我之前也踩过Unity JsonUtility的这个坑,你的问题核心是没满足它的序列化规则,咱们一步步来搞定:

核心问题分析

Unity的JsonUtility对序列化/反序列化有几个严格要求,你的代码正好踩中了这些限制:

  • 它只能处理公共字段,无法识别带get;set;的属性
  • 不支持接口类型(比如ICollection<int>),必须用具体的数组或可序列化的集合类型
  • 反序列化时必须有无参构造函数,你的BookDTO只有带参数的构造函数,JsonUtility无法实例化对象

修正方案

1. 修正BookDTO的定义

把属性改成公共字段,替换接口类型为具体数组,添加无参构造函数:

using System;
namespace API.DTOs {
    [Serializable]
    public class BookDTO : DTO {
        // 把属性改为公共字段,去掉get;set;
        public int bookId;
        public string title;
        public string description;
        public string coverImageUrl;
        public string layout;
        // 用int[]匹配JSON中的数组结构,替换ICollection<int>
        public int[] categories;
        public int[] tags;

        // 必须添加无参构造函数,供JsonUtility反序列化调用
        public BookDTO() {}

        // 保留带参数的构造函数,不影响业务逻辑使用
        public BookDTO(int bookId, string title, string description, string coverImageUrl, string layout, int[] categories, int[] tags) {
            this.bookId = bookId;
            this.title = title;
            this.description = description;
            this.coverImageUrl = coverImageUrl;
            this.layout = layout;
            this.categories = categories;
            this.tags = tags;
        }
    }
}

2. 保留你的JsonHelper类(逻辑是正确的)

因为JsonUtility无法直接反序列化顶级数组,你的JsonHelper通过包裹成对象的方式完全没问题,无需修改:

public class JsonHelper { 
    public static T[] GetJsonArray<T>(string json) { 
        string newJson = "{ \"array\": " + json + "}"; 
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson); 
        return wrapper.array; 
    } 
    [Serializable] 
    private class Wrapper<T> { 
        public T[] array; 
    } 
}

3. 反序列化调用保持不变

BookDTO[] books; 
books = JsonHelper.GetJsonArray<BookDTO>(jsonData);

为什么之前的两种方式失败?

  • 第一种方式:使用了ICollection<int>接口和get;set;属性,JsonUtility无法识别这些类型和成员,导致反序列化出的对象全为默认值(null/0)
  • 第二种方式:错误地将JSON中的int数组当成了包含cat/tag字段的对象,而且构造函数里的手动解析逻辑完全多余,反而破坏了JsonUtility的正常反序列化流程

验证测试

用你提供的JSON数据测试,修正后的代码可以正确解析出两个BookDTO对象,所有字段都会被正确赋值,包括空的tags数组也会被初始化为空数组而非null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:54:10