Unity中Newtonsoft.Json加载自定义GraphNode字典报错求助
问题:Unity中使用Newtonsoft.Json序列化自定义类型作为键的字典加载失败
我正在开发Unity项目,需要实现键为自定义类型GraphNode、值为同类型List<GraphNode>的字典Dictionary<GraphNode, List<GraphNode>>的保存与加载功能,采用Newtonsoft.Json库进行JSON序列化与反序列化。目前保存操作可正常完成,但执行加载逻辑时触发报错:
Newtonsoft.Json.JsonSerializationException:无法将字符串'GraphNode'转换为字典键类型'GraphNode'。请创建TypeConverter以将字符串转换为键类型对象。路径'allGraphNodes.GraphNode',第5行,第16位。---> Newtonsoft.Json.JsonSerializationException:将值"GraphNode"转换为类型'GraphNode'时出错。路径'allGraphNodes.GraphNode',第5行,第16位。---> System.ArgumentException:无法从System.String强制转换或转换为GraphNode。
相关代码
GameData脚本
using System; using System.Collections.Generic; [Serializable] public class GameData { public Dictionary<GraphNode, List<GraphNode>> allGraphNodes; public GameData() { allGraphNodes = new Dictionary<GraphNode, List<GraphNode>>(); } }
GraphNode类
public class GraphNode { public enum Type { entrance = 0, enemy = 1, hub = 2, shop = 3, boss = 4 } public Type type; public GraphNode(Type type2) { SetType(type2); } public void SetType(Type type2) { type = type2; } }
保存方法
public void Save(GameData data) { string text = Path.Combine(dataDirPath, dataFileName); try { Directory.CreateDirectory(Path.GetDirectoryName(text)); string text3 = JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); if (useEncryption) { text3 = EncryptDecrypt(text3); } using FileStream stream = new FileStream(text, FileMode.Create); using StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(text3); } catch (Exception ex) { Debug.LogError("Error" + text + "\n" + ex); } }
加载方法
public GameData LoadLayout() { string text = Path.Combine(dataDirPath, dataFileName); GameData result = null; if (File.Exists(text)) { try { string text2 = ""; using (FileStream stream = new FileStream(text, FileMode.Open)) { using StreamReader streamReader = new StreamReader(stream); text2 = streamReader.ReadToEnd(); Debug.Log(text2); } if (useEncryption) { text2 = EncryptDecrypt(text2); } result = JsonConvert.DeserializeObject<GameData>(text2, new JsonSerializerSettings //important line { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); return result; } catch (Exception ex) { Debug.LogError("Error" + text + "\n" + ex); return result; } } return result; }
保存后的JSON示例
{ "$type": "GameData, Assembly-CSharp", "allGraphNodes": { "$type": "System.Collections.Generic.Dictionary`2[[GraphNode, Assembly-CSharp],[System.Collections.Generic.List`1[[GraphNode, Assembly-CSharp]], mscorlib]], mscorlib", "GraphNode": { "$type": "System.Collections.Generic.List`1[[GraphNode, Assembly-CSharp]], mscorlib", "$values": [ { "$type": "GraphNode, Assembly-CSharp", "type": 1 } ] } } }
内容的提问来源于stack exchange,提问作者Benjamin Govedarovic
相关产品推荐
相关产品推荐

