c# 反序列化递归/n叉树 json
有一个json,其某一个key包含的是自身,其实就是一个多叉树,通过NewtonsoftJson进行反序列化
json内容
[{
"id": 1,
"name": "c1",
"type": "catelog",
"text": "11",
"sub": [{
"id": 2,
"name": "s1",
"type": "catelog",
"text": "123123",
"sub": [{
"id": 3,
"name": "s2",
"type": "text",
"text": "3333",
"sub": []
}]
}]
},
{
"id": 4,
"name": "c2",
"type": "catelog",
"text": "11",
"sub": [{
"id": 5,
"name": "s5",
"type": "123123aaa",
"text": "33",
"sub": [{
"id": 6,
"name": "s6",
"type": "text",
"text": "123123",
"sub": []
}]
}]
}
]
实现方法
首先声明一个数据类
public class Result
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string text { get; set; }
public List<Result> sub { get; set; }
}
然后是解码方法
class Catelogs
{
public List<Model.Result> subs;
public void LoadSubs()
{
subs = new List<Model.Result>{ };
string myJsonResponse =File.ReadAllText(@"c:\test\text.txt");
subs = this.LoadSubs(myJsonResponse, subs);
var s = subs;
Console.WriteLine(subs);
}
private List<Model.Result> LoadSubs(string json, List<Model.Result> result)
{
JArray jar = (JArray)JsonConvert.DeserializeObject(json);
// 读取数据到Jarray 然后进行bianli
foreach (JObject item in jar)
{
var rowResult = new Model.Result();
//继续便利所有的key value
foreach (var row in item)
{
// 通过识别不同的key value进行赋值
switch (row.Key)
{
case "id":
rowResult.id = (int)row.Value;
break;
case "name":
rowResult.name = row.Value.ToString();
break;
case "type":
rowResult.type = row.Value.ToString();
break;
case "text":
rowResult.text = row.Value.ToString();
break;
case "sub":
// 如果是sub 则调用自身进行递归
rowResult.sub = new List<Model.Result> { };
this.LoadSubs(row.Value.ToString(), rowResult.sub);
break;
default:
break;
}
}
result.Add(rowResult);
}
return result;
}
}