赞
踩
实际测试发现 SimpleJSON 比 LitJson 效率要高不少,所以决定使用SimpleJSON,记录下具体使用方法。
public class SimpleJsonRootData { private List<TestData> dataList1 = new List<TestData>(); private List<TestData> dataList2 = new List<TestData>(); public void LoadData(string json) { dataList1.Clear(); dataList2.Clear(); JSONNode node = JSONNode.Parse(json); JSONNode nodeArray = SimpleJSONTools.AnalysisJsonArgument("dataList1",node); for (int i = 0; i < nodeArray.Count; i++) { TestData td = new TestData(); td.AnalysisJson(nodeArray[i]); dataList1.Add(td ); } nodeArray = SimpleJSONTools.AnalysisJsonArgument("dataList2", node); for (int i = 0; i < nodeArray.Count; i++) { TestData td = new TestData(); td.AnalysisJson(nodeArray[i]); dataList12.Add(td ); } } public void SaveData() { JSONObject nodeRoot = new JSONObject(); JSONArray nodeArray1 = new JSONArray(); for (int i = 0; i < dataList1.Count; i++) { JSONNode node = dataList1[i].GetJson(); nodeArray1.Add(node); } nodeRoot["dataList1"]=nodeArray1; JSONArray nodeArray2 = new JSONArray(); for (int i = 0; i < dataList2.Count; i++) { JSONNode node = dataList2[i].GetJson(); nodeArray2.Add(node); } nodeRoot["dataList2"]=nodeArray2; Debug.Log("nodeRoot="+nodeRoot.ToString()); } } public class TestDataBase { public int id; public string type=""; public string Id { get => id.ToString(); set { if (string.IsNullOrEmpty(value)) { Debug.Log("value="+value); } else { id = int.Parse(value); } } } public string Type { get => type; set => type = value; } public virtual JSONObject GetJson() { JSONObject node =new JSONObject(); Type t = this.GetType(); foreach (var item in t.GetProperties()) { node.Add(item.Name, item.GetValue(this,null).ToString()); } //node.Add("id",id); //node.Add("type",type); return node; } public virtual void AnalysisJson(JSONNode jsonNode) { Type t = this.GetType(); foreach (var item in t.GetProperties()) { JSONNode node = SimpleJSONTools.AnalysisJsonArgument(item.Name, jsonNode); if (node != null) { item.SetValue(this, node.Value.ToString()); } } //id = SimpleJSONTools.AnalysisJsonArgument("id", jsonNode); //type = SimpleJSONTools.AnalysisJsonArgument("type", jsonNode); } } public class TestData: TestDataBase { public float angle; public string Angle { get => angle.ToString(); set => angle =float.Parse(value); } public override JSONObject GetJson() { JSONObject node = base.GetJson(); //node.Add("angle", angle); return node; } } public class SimpleJSONTools { public static JSONNode AnalysisJsonArgument(string key, JSONNode node) { if (node.HasKey(key)) { return node[key]; } else { Debug.LogErrorFormat("AnalysisJsonArgument: '{0}' not has,json = {1}", key, node.ToString()); return null; } } }
item.SetValue(this, node.Value.ToString())
这个方法,没有找到怎么直接区分value的类型,只能选择都转成了字符串,等待评论区大神指路。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。