使用List封装的JsonObject等类的读取方法

例如:

JSONObject first = new JSONObject();

first.put("first", 1);

first.put("first2", 2);

first.put("first3", 3);


JSONObject second = new JSONObject();

second.put("second", first);


JSONObject third = new JSONObject();

third.put("third", second); ////现在JSONObject类对象third是一个由三层JSONObject构成的


则其读取方法可采用如下:

public List readJSONObject( JSONObject json ){

List<Object> result = new ArrayList<Object>();

int type = 5;

JSONObject origin = json.getJSONObject( "third" ).getJSONObject("second"); ////此时origin和first是相同的

//若json是List>形式,则采用JSONObject rst= (Double) json.get(i).get(1)进行读取

List list = getObject(origin, type);

result.addAll(list);

}

public List getObject(JSONObject json, int type ){

List<Object> result = new ArrayList>();
for(Object k : json.keySet()) { ////依次读取json中数据

String key = (String) k; // String[] spaces = query.split(","); //对于用某符号分割的字符串采用此法

Integer add1 = origin.optInt(key, 0)+1; // for(String space : spaces) { }

JSONObject rst = new JSONObject();

rst.put(key, add1);

result.add(rst);

}

return result;

}


你可能感兴趣的:(编程经验)