--
JSON类型数据用于前后台传参以及redis数据存储等方面,注解@responseBody和@requestBody已解决了前后台JSON数据转对象的操作,但是后台也有些转bean、list、map等类型数据的需求,于是一起在此作总结:
--
Json的三种数据格式
对象格式
格式:{name:value,name:value}
案例:var pp={"id":10,"name":"lisi",.......}
注意:在json数据格式中,name类型是字符串,value类型是Object。
数组格式
格式:[元素,元素,元素]
案例:var pp=[{"name":"Michael","age":24},{"name":"Tom","age":25}]
注意:取值方式,通过pp[0].name取值,值为Michael。
组合格式(嵌套)
案例:{"name":"Michael", "birthday":{"month":8,"day":26}}
Json常用的两种方法
JSON.stringify():将JSON对象转为JSON字符串(序列化)
JSON.parse():将JSON字符串转为JSON对象(反序列化,javaBean需要实现Serializable接口)
Json转bean、list、map
JSON转bean
String ssd = joData.getString("shopSelldetail");
JSONObject object3 = JSONObject.fromObject(ssd);
ShopSelldetail shopSelldetail = (ShopSelldetail)JSONObject.toBean(object3,ShopSelldetail.class);
JSON转list
List<ShopRefundrecord> refundList = new ArrayList<ShopRefundrecord>();
String refundLists = joData.getString("refundList");
JSONArray jsonArray1 = JSONArray.fromObject(refundLists);
for(int i = 0; i < jsonArray1.size(); i++){
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
ShopRefundrecord srr = (ShopRefundrecord) JSONObject.toBean(jsonObject2, ShopRefundrecord.class);
refundList.add(srr);
}
JSON转map
Map<Integer, Integer> refoundRecordMap = new HashMap<Integer, Integer>();
String refoundRecordMaps = joData.getString("refoundRecordMap");
JSONObject jsonObject = JSONObject.fromObject(refoundRecordMaps);
Iterator keys = jsonObject.keys();
while(keys.hasNext()){
Integer key = Integer.parseInt(keys.next().toString());
Integer value = Integer.parseInt(jsonObject.get(""+key).toString());
refoundRecordMap.put(key, value);
}