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

Unity自定义Json.NET转换器反序列化令牌报错,求正确实现方式

问题原因

你遇到的错误核心是:遍历jObject.Children()得到的是JProperty类型的token(对应JSON中的键值对结构),而不是直接的实体数据JObject。当你调用token.ToObject(type)时,Json.NET会尝试把包含属性名的JProperty结构反序列化为目标实体类,这就会触发"Unexpected token while deserializing object: PropertyName"错误——实体类只需要键对应的值部分,不需要处理属性名本身。

正确的Read()方法实现

修改遍历逻辑,先将token转换为JProperty,提取出属性名(作为dataKey)和对应的Value(真正要反序列化的JObject数据),再对Value执行反序列化:

public override Data ReadJson(JsonReader reader, Type objectType, Data existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
{
    // 加载当前对应的JObject(这里对应JSON中"Data"字段的内容)
    JObject jObject = JObject.Load(reader);

    Data data = hasExistingValue ? existingValue : new Data();

    foreach (JToken token in jObject.Children())
    {
        // 将token转换为JProperty,分离键与数据部分
        JProperty property = token as JProperty;
        if (property == null) continue;

        string dataKey = property.Name; // 对应JSON中的"DataTypeOne"/"DataTypeTwo"
        JToken dataValue = property.Value; // 对应具体的实体数据JObject

        // 根据键获取目标类型
        Type targetType = GetTypeByKey(dataKey);
        if (targetType == null) continue;

        // 对数据部分执行反序列化
        ISaveableData deserializedInstance = dataValue.ToObject(targetType, serializer) as ISaveableData;
        if (deserializedInstance == null) continue;

        // 添加到Data的字典容器中(根据你的Data类结构调整)
        data.DataDictionary[dataKey] = deserializedInstance;
        // 如果你的Data类有封装的Add方法,也可以用:
        // data.Add(dataKey, deserializedInstance);
    }
    
    return data;
}
额外注意事项
  • 确保GetTypeByKey(dataKey)能正确根据属性名映射到对应的具体类型(比如"DataTypeOne"对应DataTypeOne类)。
  • 增加空值判断(如property == null、deserializedInstance == null),避免空引用异常,提升系统健壮性。
  • 若你的Data类的Add方法需要同时接收键和值,需对应调整代码逻辑,避免丢失dataKey信息。

内容的提问来源于stack exchange,提问作者Meister der Magie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:52:45