java解析多层json
有个json数据,如何解析。
{'name':'111','child':[{'name':'222','child':[{'name':'333'}]},{'name':'2221'}]}
------解决方案--------------------直接用net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject("");
------解决方案--------------------一对花括号离得数据相当于一个json
用net.sf.json.JSONObject 对象的fromObject(String) 方法转换你的json文件,
方括号中的数据用jsonarray获取
------解决方案--------------------参考代码(只解析了第一层的child数组,嵌套的层次可以类似的方法解析):
String jsonStr = "?{'name':'111','child':[{'name':'222','child':[{'name':'333'}]},{'name':'2221'}]}";
JSONObject jsonObj = JSONObject.fromObject(jsonStr);
JSONArray jsonArray = jsonObj.getJSONArray("child");
if (null != jsonArray && jsonArray.size() > 0) {
for (int i = 0; i < jsonArray.size(); i++) {
Object obj = jsonArray.get(i);
JSONObject json = JSONObject.fromObject(obj);
if (StringUtils.isNotBlank(json.getString("name"))) {
log.info("name "+json.getString("name"));
}
}
------解决方案--------------------package com.xyj.test;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class JsonAnalysisTest {
private String jsonData;
class People {
private String name;
private People people;
private List<People> list;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
public List<People> getList() {
return list;
}
public void setList(List<People> list) {
this.list = list;
}
public People(String name) {
this.name = name;
}
public People(String name, List<People> list) {
this.name = name;
this.list = list;
}
}
/**
* 生成json格式的数据
*/
public void createJsonData() {
People p1 = new People("111");
People p2 = new People("222");
People p3 = new People("333");
People p4 = new People("444");
List<People> list = new ArrayList<People>();
list.add(p3);
list.add(p4);
p2.setList(list);
p1.setPeople(p2);
Gson gson = new Gson();
jsonData = gson.toJson(p1);
analysisJsonData(jsonData);
System.out.println(jsonData);
}
/**
* 解析json格式的数据
*/
public void analysisJsonData(String data) {
Gson gson = new Gson();
People p = gson.fromJson(data, People.class);
System.out.println(p.getName());
System.out.println(p.getPeople().getName());
List<People> list = p.getPeople().getList();
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i).getName());
}
}
public static void main(String[] args) {
new JsonAnalysisTest().createJsonData();
}
}
------解决方案-------------------- JSONObject jasonObject = JSONObject.fromObject(jdon);
Map map = (Map)jasonObject;
Set<String> key = map.keySet();
String userid = "";
for (Iterator it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
Map map2 = (Map) map.get(s);
可以考虑先将json转换成Map接下来的事情相信你会了