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

Unity构建版本中NewtonSoft JSON反序列化失效问题排查

Unity构建版本JSON反序列化构造函数问题解决方案

核心排查与解决步骤

1. 确保代码序列化可见性

Unity构建时的代码裁剪(IL2CPP/Mono剥离)可能把构造函数优化掉,必须保证类和构造函数的可见性:

  • 给POIListCollection和PointOfInterest类加上[System.Serializable]特性,同时类和构造函数都设为public:
    [System.Serializable]
    public class POIListCollection
    {
        public List<PointOfInterest> pois;
    
        // 必须保留public无参构造
        public POIListCollection() {}
    
        [JsonConstructor]
        public POIListCollection(List<PointOfInterest> pois)
        {
            this.pois = pois;
        }
    }
    
    [System.Serializable]
    public class PointOfInterest
    {
        // 你的业务字段示例
        public string id;
        public string name;
    
        public PointOfInterest() {}
    
        [JsonConstructor]
        public PointOfInterest(string id, string name)
        {
            this.id = id;
            this.name = name;
        }
    }
    

2. 阻止代码裁剪移除关键代码

如果用IL2CPP后端,代码剥离大概率是元凶,两种解决方式:

  • 临时关闭裁剪:打开PlayerSettings → Optimization → Managed Stripping Level,改成Disabled测试,后续可调回Low。
  • 用link.xml强制保留类:在Assets目录下新建link.xml,填入以下内容(替换成你的程序集名称,比如Assembly-CSharp):
    <linker>
        <assembly fullname="Assembly-CSharp">
            <type fullname="POIListCollection" preserve="all"/>
            <type fullname="PointOfInterest" preserve="all"/>
        </assembly>
    </linker>
    

3. 确认JSON库适配性

不同JSON库在Unity构建中的表现差异很大:

  • 如果你用Unity自带的JsonUtility:它不支持[JsonConstructor]特性,只认无参构造,且字段必须是public或加[SerializeField],直接去掉带参构造的[JsonConstructor],用无参构造+字段赋值的方式序列化。
  • 如果你用Newtonsoft Json:必须用Unity官方适配的包(在Package Manager中安装com.unity.nuget.newtonsoft-json),不要自己导入dll,避免构建时被裁剪。

4. 校验JSON格式匹配

确保JSON字段名和类的字段名大小写完全一致,比如JSON里是"pois",类里就不能是POIs或Pois。示例正确JSON格式:

{
  "pois": [
    {"id": "1", "name": "广场"}
  ]
}

5. 查看构建日志定位细节

构建后去对应平台的日志目录找Player.log(Windows路径:%USERPROFILE%\AppData\LocalLow\你的公司名\你的游戏名),里面会有更详细的错误堆栈,确认是构造函数被移除还是字段匹配错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:10:28