using Newtonsoft.Json; using System.Collections.Concurrent; namespace LB_VisionFlowNode { // 序列化管理类 public static class FlowSerializer { public static string Serialize(ConcurrentDictionary nodes , ConcurrentDictionary connections) { var data = new FlowData { Nodes = nodes, Connections = connections }; var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; return JsonConvert.SerializeObject(data, settings); } public static (ConcurrentDictionary, ConcurrentDictionary) Deserialize(string json) { var settings = new JsonSerializerSettings { }; var data = JsonConvert.DeserializeObject(json, settings); var nodeDictionary = data.Nodes.ToDictionary(n => n.Value.Id); // 重建连接关系 foreach (var connection in data.Connections) { if (nodeDictionary.TryGetValue(connection.Value.StartNodeId, out var startNode)) connection.Value.StartNode = startNode.Value; if (nodeDictionary.TryGetValue(connection.Value.EndNodeId, out var endNode)) connection.Value.EndNode = endNode.Value; } //// 重建 NextNode 关系 //foreach (var node in data.Nodes) //{ // foreach (var branchNodeName in node.Value.BranchNodes.Values) // { // if (!string.IsNullOrEmpty(branchNodeName) && // nodeDictionary.TryGetValue(branchNodeName, out var nextNode)) // { // node.Value.NextNode = nextNode.Value; // } // } //} return (data.Nodes, data.Connections); } } // 包装类用于序列化 public class FlowData { [JsonProperty("Nodes")] public ConcurrentDictionary Nodes { get; set; } = new ConcurrentDictionary(); [JsonProperty("Connections")] public ConcurrentDictionary Connections { get; set; } = new ConcurrentDictionary(); } }