基本的JSONArray与JSONObject操作:
JSONObject jsonObj =new JSONObject();
jsonObj.put("name0", "zhangsan");
jsonObj.put("sex1", "female");
System.out.println(jsonObj); //输出为:{"sex1":"female","name0":"zhangsan"}
JSONArray jsonArray =new JSONArray();
jsonArray.add("11");
jsonArray.add("22");
jsonArray.add("33");
System.out.println(jsonArray); //输出为:["11","22","33"]由java自带的数据结构转换为JSON文本:
JSONArrayString list[]={"11","22"};
JSONArray jsonarray = JSONArray.fromObject(list);
jsonarray.add("33");
System.out.println(jsonarray); //输出为:["11","22","33"]
//可以由Map生成JSONObjectMap map=newHashMap();
map.put("NO1", "第一个");
map.put("NO2", "第二个");
map.put("NO3", jsonarray);
JSONObject jsonObj = JSONObject.fromObject(map);
System.out.println(jsonObj); //输出为:{"NO3":["11","22","33"],"NO2":"第二个","NO1":"第一个"}读取JSON文本:
JSONArray jsonarray;
JSONObject jsonObj;
//读取JSONArray,用下标索引获取String array="[\"11\",\"22\",\"33\"]";
jsonarray = JSONArray.fromObject(array);
System.out.println(jsonarray.getString(1));//输出为:22
//读取JSONObjectString object="{\"NO1\":[\"44\",\"55\",\"66\"],\"NO2\":{\"NO1\":\"第一个\"}}";
jsonObj = JSONObject.fromObject(object);
System.out.println(jsonObj.get("NO1"));//输出为:["44","55","66"]
jsonarray = (JSONArray)(jsonObj.get("NO1"));
System.out.println(jsonarray.getString(1));//输出为:55
//用"键"获取值jsonObj=(JSONObject)jsonObj.get("NO2");
System.out.println(jsonObj); //输出为:{"NO1":"第一个"}
随时随地看视频