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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值