chararray遍历_从文件读入树状jsonArray数据,并遍历

本文介绍了如何使用Java处理JSON数组,包括线性表状及树状结构的遍历方法,并提供了一个递归函数来处理多级嵌套的JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用到处理json的jar包:

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

一、线性表状的json数组遍历:

如果你的数据不存在某个key对应的value是数组,以下代码即可遍历整个json数组:

Iterator it = ja.iterator();

while (it.hasNext()){

JSONObject ob = (JSONObject) it.next();

}

二、树状的json数组的遍历。

先给大家看一下我的json数据。

[

{

"name": "Grandpa",

"value": "20",

"children": [

{

"name": "Uncle Leo",

"value": 15,

"children": [

{

"name": "Cousin Jack",

"value": 2

},

{

"name": "Cousin Mary",

"value": 5,

"children": [

{

"name": "Jackson",

"value": 2

}

]

},

{

"name": "Cousin Ben",

"value": 4

}

]

},

{

"name": "Father",

"value": 10,

"children": [

{

"name": "Me",

"value": 5

},

{

"name": "Brother Peter",

"value": 1

}

]

}

]

},

{

"name": "Nancy",

"value": "15"

}

]

1、首先从文件中读取数据

String jsonStr = null;

try {

File file = new File("path");

FileReader fileReader = new FileReader(file);

Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");

int ch = 0;

StringBuffer sb = new StringBuffer();

while ((ch = reader.read()) != -1) {

sb.append((char) ch);

}

fileReader.close();

reader.close();

jsonStr = sb.toString();

} catch (Exception e) {

System.out.println("获取 json 文件出错 ");

}

JSONArray jsonArray = JSONArray.fromObject(jsonStr); //把读取到的数据存成json数组格式

2、用JSONArray包里面封装的iterator函数对json数组遍历,注意它并不是调用一下就可以全部遍历了,他只会把这个数组的第一维遍历,如果把json数组比作一个森林的话,他遍历的只是这个森林的每棵树的第一个节点。 例如我上面的数据中,他只会遍历Grandpa和Nancy。所以要加一个递归函数。

Iterator it= jsonArray.iterator();

iterJsonArr(it,0);//递归函数

3、递归函数。

public void iterJsonArr(Iterator it,Integer pid){ //递归遍历json数组 。

while (it.hasNext()){

JSONObject ob = (JSONObject) it.next();

if (ob.has("children")){//判断是否有孩子节点,如果有,就递归遍历

JSONArray jsonArray= (JSONArray) ob.get("children");

Iterator c_it= jsonArray.iterator();

iterJsonArr(c_it,tree.getId());

}

}

}

以上。如有不懂或有好的json数据处理方式欢迎交流学习!!!嘿嘿嘿

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值