能否让System.Text.Json.JsonSerializer以非递归方式工作?
图结构JSON序列化与反序列化问题
结构定义
public class Whole { public List<Node> allPossibleNodes = new List<Node>(); } public class Node { public List<Node> neighbors = new List<Node>(); }
序列化实现代码
public class WriteTest { static JsonSerializerOptions options = new () { WriteIndented = true, IncludeFields = true, IgnoreReadOnlyProperties = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, ReferenceHandler = ReferenceHandler.Preserve, }; public static void write() { var w = new Whole(); Node? p = null; //previous for (int i = 0; i < 3; i++) { var n = new Node(); w.allPossibleNodes.Add(n); if (p != null) { n.neighbors.Add(p); p.neighbors.Add(n); } p = n; } var json = JsonSerializer.Serialize(w, options); File.WriteAllText("test.json", json); } public static void read() { var json = File.ReadAllText("test2.json"); var w = JsonSerializer.Deserialize<Whole>(json, options); } }
当前遇到的问题
- 序列化时抛出
JsonException:JsonException: 'A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64.,若设置options.MaxDepth = Int.MaxValue则可能引发栈溢出; - 生成的JSON可读性极差。
期望的JSON格式
{ "$id": "1", "allPossibleNodes": { "$id": "2", "$values": [ { "$id": "3", "neighbors": { "$id": "6", "$values": [ { "$ref": "4" } ] } }, { "$id": "4", "neighbors": { "$id": "7", "$values": [ { "$ref": "3" }, { "$ref": "5" } ] } }, { "$id": "5", "neighbors": { "$id": "8", "$values": [ { "$ref": "4" } ] } } ] } }
疑问
上述格式的JSON无法被反序列化,会报错'Reference '4' was not found...,请问是否有办法实现该格式的序列化与反序列化?
内容的提问来源于stack exchange,提问作者Pawulon
相关产品推荐
相关产品推荐

