[{
"info": {
"users": {
"username": "东升布艺","email": "jilongliang@sina.com","tel": "111111111","age": "25"
},"address": {
"street": "云城区闻莺路东升布艺","province": "广东省","district": "云城区","city": "云浮市"
}
}
}]
package ivyy.taobao.com.domain.fastjson;
import java.util.Iterator;
import ivyy.taobao.com.utils.IoUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
*@DEMO:json
*@Java:JSONTest3.java
*@Date:2015-1-19上午9:44:14
*@Author:liangjilong
*@Email:jilongliang@sina.com
*@Weibo:http://weibo.com/jilongliang
*@Version:1.0
*@Description:通过fastjson的JSON对象类处理json数组数据
*/
public class JSONTest3 {
public static void main(String[] args) {
//1、处理文件路径
String filePath=JSONTest3.class.getClassLoader().getResource("doc/json1.json").getPath();
//2、读取文件里面的数据
String content=IoUtils.reader(filePath);
//3、把数据转换成json数组
JSONArray jarr=JSON.parseArray(content);
//-----------------------------方法一-----------------------------
//遍历json数组节点
for (Iterator iterator = jarr.iterator(); iterator.hasNext();) {
JSONObject object = (JSONObject) iterator.next();
//拿出info节点
JSONObject infoObj=JSON.parSEObject(object.get("info").toString());
//拿出address节点
JSONObject addrObj=JSON.parSEObject(infoObj.get("address").toString());
System.out.println(addrObj.get("province"));//拿出province节点
System.out.println(addrObj.get("city"));//拿出city节点
System.out.println(addrObj.get("district"));//拿出district节点
System.out.println(addrObj.get("street"));//拿出street节点
System.out.println(addrObj.getString("street"));//拿出street节点
}
//-----------------------------方法二-----------------------------
//遍历json数组节点
for (int i=0;i<jarr.size();i++) {
JSONObject object = (JSONObject) jarr.get(i);
//拿出info节点
JSONObject infoObj=JSON.parSEObject(object.get("info").toString());
//拿出address节点
JSONObject addrObj=JSON.parSEObject(infoObj.get("address").toString());
System.out.println(addrObj.get("province"));//拿出province节点
System.out.println(addrObj.get("city"));//拿出city节点
System.out.println(addrObj.get("district"));//拿出district节点
System.out.println(addrObj.get("street"));//拿出street节点
System.out.println(addrObj.getString("street"));//拿出street节点
}
//-----------------------------方法三-----------------------------
//-----------------------------还可以使用do while while..-----------------------------
//参考文章http://blog.csdn.net/jilongliang/article/details/42841811 的getArrayToJsonByMap方法
//遍历json数组节点
for (Object object : jarr) {
JSONObject obj=JSON.parSEObject( object.toString());
JSONObject infoObj=JSON.parSEObject(obj.get("info").toString());
//拿出address节点
JSONObject addrObj=JSON.parSEObject(infoObj.get("address").toString());
System.out.println(addrObj.get("province"));//拿出province节点
System.out.println(addrObj.get("city"));//拿出city节点
System.out.println(addrObj.get("district"));//拿出district节点
System.out.println(addrObj.get("street"));//拿出street节点
System.out.println(addrObj.getString("street"));//拿出street节点
}
}
}
原文链接:https://www.f2er.com/json/289911.html