(二)JAVA转JSON
1:bean—json
String json = "{\"name\":\"reiz\"}";
JSONObject jb = JSONObject.fromObject(json);
放入值
jb.put("sex", "男");
System.out.println(jb);
取值
String name = jb.getString("name");
System.out.println(name);
输出如下:
{"name":"reiz","sex":"男"}
reiz
2:array—json
//构造list对象
List<ResInfo> listResInfo = new ArrayList<ResInfo>();
ResInfo resInfo = new ResInfo();
resInfo.setResName("名字一");
resInfo.setOwnerName("作者一");
ResInfo resInfo2 = new ResInfo();
resInfo2.setResName("名字二");
resInfo2.setOwnerName("作者二");
listResInfo.add(resInfo);
listResInfo.add(resInfo2);
//转换list为json
JSONArray jb2 = JSONArray.fromObject(listResInfo);
//添加参数
jb2.add("参数");
System.out.println(jb2);
输出结果
[{"ownerName":"作者一","resName":"名字一"},{"ownerName":"作者二","resName":"名字二"},"参数"]
(二)JSON
1:json 取 bean 数据
String json = "{\"id\":\"123\",\"name\":\"haha\"}";
JSONObject obj = JSONObject.fromObject(json);
String userid = obj.getString("name");
System.out.println("userId is:" + userid);
输出结果:
userId is:haha
2:json 取 array 数据
String array = "[{\"id\":\"123\",\"name\":\"haha\"},{\"id\":\"456\",\"name\":\"hehe\"}]";
JSONArray jb3 = JSONArray.fromObject(array);
for(int i=0;i<jb3.size();i++){
System.out.println("-----"+jb3.get(i));
}
输出结果:
-----{"id":"123","name":"haha"}
-----{"id":"456","name":"hehe"}
3:json 是bean,包含 array 的情况
//json包含数组
String json = "{x:'1',y:'2',userId:'112',element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}";
JSONObject object = JSONObject.fromObject(json);
//取出数组
JSONArray array = object.getJSONArray("element");
//循环迭代
for(int i=0;i<array.size();i++){
System.out.println(array.get(i));
//取出每一个对象
JSONObject obj2 = JSONObject.fromObject(array.get(i));
System.out.println(obj2.getString("name"));
}
输出结果:
{"id":"123","name":"haha"}
haha
{"id":"456","name":"hehe"}
hehe