最近在Unity中使用时遇到的问题,继承IEnumable接口导致反序列化失败,经过多方查找解决了.
下图调用 JsonConvert.PopulateObject();一直报错,反复对照json文件,并没有发现什么问题.
解决方案如下(我这里是使用默认解析比较方便,当然自定义解析也可以解决.),更详细的问题根源,继续往下.
下方代码是json.net,反序列化构造对象的过程.(可以看到JsonObject转换顺序在上方,高于IEnumerable).
源码链接:https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L1218
////// Determines which contract type is created for the given type. /// /// Type of the object. ///A protected virtual JsonContract CreateContract(Type objectType) { Type t = ReflectionUtils.EnsureNotByRefType(objectType); if (IsJsonPrimitiveType(t)) { return CreatePrimitiveContract(objectType); } t = ReflectionUtils.EnsureNotNullableType(t); JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetCachedAttributefor the given type. (t); if (containerAttribute is JsonObjectAttribute) { return CreateObjectContract(objectType); } if (containerAttribute is JsonArrayAttribute) { return CreateArrayContract(objectType); } if (containerAttribute is JsonDictionaryAttribute) { return CreateDictionaryContract(objectType); } if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken))) { return CreateLinqContract(objectType); } if (CollectionUtils.IsDictionaryType(t)) { return CreateDictionaryContract(objectType); } if (typeof(IEnumerable).IsAssignableFrom(t)) { return CreateArrayContract(objectType); } if (CanConvertToString(t)) { return CreateStringContract(objectType); } #if HAVE_BINARY_SERIALIZATION if (!IgnoreSerializableInterface && typeof(ISerializable).IsAssignableFrom(t) && JsonTypeReflector.IsSerializable(t)) { return CreateISerializableContract(objectType); } #endif #if HAVE_DYNAMIC if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(t)) { return CreateDynamicContract(objectType); } #endif #if HAVE_ICONVERTIBLE // tested last because it is not possible to automatically deserialize custom IConvertible types if (IsIConvertible(t)) { return CreatePrimitiveContract(t); } #endif return CreateObjectContract(objectType); }
结语:好了反序列化也解决了,如果出现反序列化失败了,可以回头看看构造的顺序.



