Newtonsoft.Json 与 TreeNode

不去试,总是活在[我以为]中。映像中看过一本书说 Unity 在处理形如 TreeNode 这样的数据结构的序列化时会玩出死循环,所以使用 Json 序列化与反序列化TreeNode 结构以为存在引用嵌套啊,循环引用啊,等等技术壁垒,今天同事在问,就试了一下,发现 Newtonsoft.Json 原生就支持嘛。

TreeView 与 TreeNode

using System.Collections.Generic;
using Newtonsoft.Json;

public class TreeView
{
    public List<TreeNode> ChildNodes = new List<TreeNode>();
}

public class TreeNode  {
    public string Name { get; set; } //节点名称
    public bool IsExpand { get; set; } //是否展开
    public bool IsSelected { get; set; } //是否选中
    [JsonIgnore]
    public object CustomData { get; set; } //用户绑定的数据
    [JsonIgnore]
    public bool HasChild { get { return ChildNodes.Count > 0; } } //是否存在子节点
    public List<TreeNode> ChildNodes = new List<TreeNode>();
}

TestFill

using UnityEngine;
using Newtonsoft.Json;
using System.IO;
using System.Text;

public class TsetFill : MonoBehaviour
{
    void Start()
    {
        TreeView treeView = new TreeView();
        for (int i = 0; i < 4; i++)  //一级菜单4个
        {
            TreeNode item = new TreeNode();
            treeView.ChildNodes.Add(item);
            FillTreeNode(item); //递归添加菜单,深度为4个层级
            depth = 1;
        }
        string data = JsonConvert.SerializeObject(treeView, Formatting.Indented);
        string path = Application.dataPath + "/" + "11.json";  
        if (!File.Exists(path))
        {
            using (StreamWriter writer = File.CreateText(path)) //写数据
            {
                writer.WriteLine(data);
            }
        }
        else
        {
            File.WriteAllText(path, data, Encoding.UTF8); //覆盖数据
        }
    }
    int depth = 1;
    private void FillTreeNode(TreeNode tree)
    {
        if (depth < 4)
        {
            depth++;
            for (int i = 0; i < 4; i++)
            {
                TreeNode item = new TreeNode();
                tree.ChildNodes.Add(item);
                FillTreeNode(item);
            }
        }
    }
}

用于测试像 Treeview 中 填充数据。得到的数据如下:


3600713-7a0d34989fd56b79.png

TestDe

using UnityEngine;
using Newtonsoft.Json;
public class TestDe : MonoBehaviour {
    public TextAsset json;
    TreeView tree;
    private void Start()
    {
        if (null!=json&&!string.IsNullOrEmpty(json.text))
        {
            tree = JsonConvert.DeserializeObject<TreeView>(json.text);
            Debug.Log(tree.ChildNodes[0].ChildNodes[0].ChildNodes[0]);
        }
    }
}
用于测试 反序列化,反序列化效果如下:
3600713-a40ad8f9f9bd8989.png

写到最后:

这是一个笔记,希望能对读者有所帮助吧~

猜你喜欢

转载自blog.csdn.net/weixin_34087503/article/details/86858512