ArrayList 转化成 JSONArray :
net.sf.json.JSONArray result = JSONArray.fromObject(arrayList);
com.alibaba.fastjson.JSONArray result = JSON.parseArray(JSON.toJSONString(arrayList));
String pic = "[{"picServiceUrl": "0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage": "1","name":null},{"picServiceUrl": "d0a7a8c24c0e463eb9ece1a7076af0e1/20180516/243598","mainPage": "0"}]";
String 可以转化成一个 JSONArray 的数组:
JSONArray array = JSONArray.fromObject(pic);
array 是:
[{"picServiceUrl":"0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage":"1","name":null},{"picServiceUrl":"d0a7a8c24c0e463eb9ece1a7076af0e1/20180516/243598","mainPage":"0"}]
array.get(0).getClass().getName() 的类型是 net.sf.json.JSONObject
取出 array 数组中的元素,可以转化成 JSONObject :
JSONObject json = (JSONObject) array.get(0);
json 的值是 : {"picServiceUrl":"0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage":"1","name":null}
accumulate 方法 可以给 JSONObject 增加一个key,value 。如果之前对象存在该 key, 则会 把现在的 value 和 之前的 value 组成一个数组,当作该key 的value 值。
json.accumulate("name", 11);
json 的值是: {"picServiceUrl":"0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage":"1","name":[null,11]}
put 和 element 方法也会给 JSONObject 增加一个key,value 。但是 如果之前对象存在该 key,则会把 之前的value 改成新的 value:
json.put("name", "zhangsan");
json 的值是:{"picServiceUrl":"0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage":"1","name":"zhangsan"}
获取key的value值:
System.out.println(json.get("picServiceUrl")); 输出:0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329
把 String转化成 JSONArray 对象后,也可以把数组中的元素转化成 Map<String, Object> 对象:
String pic = "[{"picServiceUrl": "0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage": "1","name":null},{"picServiceUrl": "d0a7a8c24c0e463eb9ece1a7076af0e1/20180516/243598","mainPage": "0"}]";
JSONArray array = JSONArray.fromObject(pic);
Map<String, Object> object = (Map<String, Object>) array.get(0);
System.out.println(object); // 输出: {"picServiceUrl":"0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329","mainPage":"1","name":12.36}
System.out.println(object.get("picServiceUrl")); // 输出: 0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329
如果 类ServiceGoodsPicture 中含有 private String picServiceUrl; 和 private Boolean mainPage; 两个属性,则 可以把 object 转化成 ServiceGoodsPicture 的一个对象:
ServiceGoodsPicture entity = ClassUtil.mapToEntity(ServiceGoodsPicture.class, object);
System.out.println(entity); // entity.toString() 输出:
ServiceGoodsPicture [Hash = 31, sid=null, serviceId=null, picServiceUrl=0f4bb44afb2e48d48b786d3bbdeec283/20180408/695329, picCreateTime=null, mainPage=true, sort=null, serialVersionUID=1]