解析json字符串
1.获取json数据,这里就举例吧
2.导入相关的夹包,注意版本统一 ,commons-beanutils-1.8.1.jar、commons-collections-3.2.1.jar、commons-lang-2.4.jar、commons-logging-1.1.1.jar、ezmorph-1.0.6.jar、ezmorph-1.0.6.jar、ezmorph-1.0.6.jar、ezmorph-1.0.6.jar
3.两种格式[]、{}
4.以{}开头使用JSONObject.fromObject(“json数据”),将json数据转为java对象、以[]开头使用JSONArray.fromObject(“json数据”),将json数据转为java数组
public class TestJieXiJson {
private static final String TEST_JSON="{\"ch\": [{\"names\":\"怡美家园\",\"data\":[2,2,1,1,1,1],\"times\":[10,11,13,13,21,23]},{\"names\":\"怡美家园\",\"data\":[2,2,1,1,1,1],\"times\":[10,11,13,13,21,23]}]}";
public static void Test3(){
//将json字符串转为java对象
JSONObject json=JSONObject.fromObject(TEST_JSON);
//取ch的数组
JSONArray jsonArray = json.getJSONArray("ch");
for (int i = 0; i < jsonArray.size(); i++) {
//得到ch中的每个对象
JSONObject json1 = jsonArray.getJSONObject(i);
//取属性为names的值
String names=json1.getString("names");
System.out.println("names"+"---"+names);
//取json1对象中data的数组
JSONArray jsonArray2 = json1.getJSONArray("data");
//取json1对象中data的数组
JSONArray jsonArray3 = json1.getJSONArray("times");
//循环遍历jsonArray2
for (int j = 0; j < jsonArray2.size(); j++) {
//去对应的值
String data=jsonArray2.getString(i);
System.out.println("data"+"---"+data);
}
//循环遍历jsonArray3
for(int j = 0; j < jsonArray3.size(); j++){
String times=jsonArray3.getString(i);
System.out.println("times"+"---"+times);
}
}
}
public static void main(String[] args) {
TestJieXiJson.Test3();
}
}