using Newtonsoft.Json;
|
using System.Collections.Concurrent;
|
|
namespace LB_VisionFlowNode
|
{
|
// 序列化管理类
|
public static class FlowSerializer
|
{
|
public static string Serialize(ConcurrentDictionary<string, FlowNode> nodes
|
, ConcurrentDictionary<string, FlowConnection> 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<string, FlowNode>, ConcurrentDictionary<string, FlowConnection>) Deserialize(string json)
|
{
|
var settings = new JsonSerializerSettings { };
|
|
var data = JsonConvert.DeserializeObject<FlowData>(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<string, FlowNode> Nodes { get; set; }
|
= new ConcurrentDictionary<string, FlowNode>();
|
|
[JsonProperty("Connections")]
|
public ConcurrentDictionary<string, FlowConnection> Connections { get; set; }
|
= new ConcurrentDictionary<string, FlowConnection>();
|
}
|
}
|