博客背景是Java开发。json相关的转换、取值等在日常开发中经常使用,但有时候还是会忘记or遇到些奇奇怪怪的问题。以此记录,提醒自己~不定期更新~
文章目录
1、JSONObject相关
实体类和JSONObject互转
//实体类转为JSONObjectJSONObject jsonObject = JSON.toJSON(entity);JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(entity));//JSONObject转为实体类Entity entity = JSONObject.toJavaObject(jsonObject, Entity.class);
Map和JSONObject互转
//Map转为JSONObjectJSONObject jsonObject = JSON.toJSON(map);JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));//JSONObject转为MapMap map = JSONObject.toJavaObject(jsonObject, Map.class);
String转JSONObject
JSONObject jsonObject = JSONObject.fromObject(stringText);
实体类转JSON字符串时不过滤NULL空值
String jsonStr = JSONObject.toJSONString(VO,SerializerFeature.WriteMapNullValue);
获取JSONObject中的key value
JSONObject baseInfo = jsonObject.getJSONObject("detail");// 遍历基本信息for (Map.Entry entry : baseInfo.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue());}
2、JSONArray相关
List和JSONArray互转
//List转为JSONArrayJSONArray jsonArray = JSON.toJSON(list);JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));//JSONArray转为ListList list = JSONObject.parseArray(jsonArray.toJSONString(), Entity.class);
List
//List
JASONArray转为JSONObject
JSONArray result_type = new JSONArray();StringBuffer selectType = new StringBuffer();selectType.append(" select id from table");result_type = jdbcTemp.queryForJSONArray(selectType.toString());JSONObject jsonObject = new JSONObject();for (int i = 0; i < result_type.size(); i++) { JSONObject jsonObject = (JSONObject) result_type.get(i);}return jsonObject;
解决问题:JASONArray转为JSONObject只返回了最后一个JSONObject
StringBuilder builder = new StringBuilder(); //业务代码//转换for (int i = 0; i < jsonArray.size(); i++) { jsonObject = (JSONObject) jsonArray.get(i); builder.append(jsonObject).append("\n"); } //业务代码return builder.toString();
String转JSONArray
JSONArray jsonArray = JSONArray.fromObject(stringText);
3、Object相关
Object转JSONObject
JSONObject json = (JSONObject) JSONObject.toJSON(list.get(0));
Object转List
//Object转Listpublic static List objToList1(Object obj) throw CoreException{List result = new ArrayList(); if (obj instanceof ArrayList>) { for (Object o : (List>) obj) { result.add(String.class.cast(o)); } } return result;} //通用工具类 public static List objToList(Object obj, Class cla) throw CoreException{List list = new ArrayList(); if (obj instanceof ArrayList>) { for (Object o : (List>) obj) { list.add(cla.cast(o)); } return list; } return null;} //调用 List list = objToList(obj,String.class);//注意:int.class = Integer.TYPE !=Integer.class
来源地址:https://blog.csdn.net/weixin_44436677/article/details/131269751