json 数据循环
1.首先需要写三个类,这个类和json中对象的数据结构应该是对应的,这里的例子可能忽略了部分属性和数据类型,仅供参考:
//Json数据的对象结构
public class MyJson
{
public List<MyTreeNodeBean> beanList { get; set; }
}
//树形结构中的对象结构
public class MyBean
{
public string id { get; set; }
public string title { get; set; }
public string note { get; set; }
public MyImage image { get; set; }
public string maxid { get; set; }
public string fold { get; set; }
public string putright { get; set; }
public List<MyTreeNodeBean> children { get; set; }
public MyBean()
{
}
}
//对象里面Image的结构
public class MyImage
{
public string url { get; set; }
public string border { get; set; }
public string height { get; set; }
public string width { get; set; }
}
2.因为json是树形结构的数据,所以需要递归遍历去寻找对应ID的对象
//这个类负责按照ID寻找对象
public class MyHelper
{
//FindById函数的重载函数,用来第一次调用
public static MyBean FindById(string id, string jsonString)
{
return FindById(id, jsonString, null);
}
//FindById递归寻找函数
public static MyBean FindById(string id, string jsonString, List<MyBean> beanList)
{
if (beanList == null) {
//第一次调用的时候,寻找的列表是最高层的根底下的对象列表
//将json数据转换成C#对应类型(用了Newtonsoft.Json)
MyJson json = JavaScriptConvert.DeserializeObject<MyJson>(jsonString);
beanList = json.beanList;
}
//遍历对象列表,寻找对应ID的对象
MyBean returnBean = null;
foreach (MyBean bean in beanList) {
if (bean.id == id) {
//找到了
returnBean = bean;
} else {
//递归寻找:
//如果不是,就寻找此对象的children列表
returnBean = FindById(id, jsonString, bean.children);
}
//如果找到,就跳出寻找
if (returnBean != null) {
break;
}
}
return returnBean;
}
}
3.使用实例:
//假设json的字符串在变量jsonString中
MyBean bean = MyHelper.FindById("33", jsonString);
if (bean != null) {
//使用查找出来的bean
}