不去试,总是活在[我以为]中。就像以前总以为Treeview 中TreeNode 用 json 序列化与反序列化存在什么技术壁垒,今天试了一下,发现 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 中 填充数据。得到的数据如下:

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]);
}
}
}
用于测试 反序列化,反序列化效果如下:

写到最后:
这是一个笔记,希望能对读者有所帮助吧~
网友评论