1. 常用的JSON转换
- JSONObject 转 JSON 字符串
JSONObject json = new JSONObject();
jsonObject.put("name", "test");
String str = JSONObject.toJSONString(json);
- JSON字符串转JSON
String str = "{\"name\":\"test\"}";
JSONObject json = JSONObject.parseObject(str);
- 实体类转JSON
Test test = new Test();
test.setName("test");
String testStr = JSONObject.toJSONString(test);
JSONObject json = JSONObject.parseObject(testStr);
- JSON转实体类
JSONObject jsonObject = JSONObject.parseObject(str);
Entity entity = JSON.toJavaObject(userJson,Entity.class);
- Map转JSON
JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
- JSON转Map
Map jsonToMap = JSONObject.parseObject(jsonObject.toJSONString());
2. 将多个JSON合并一个
JSONObject totalJSON = new JSONObject();
totalJSON.putAll(json1);
totalJSON.putAll(json2);
json1,json2
为JSONObject。 最终的代码格式:
{
json1:{},
json2:{}
}
3.JSON拆分
不同的需求有不同的做法,以下提供两种解决思路
- 定义两个或多个JSON进行put和remove 比如明确需要哪些字段的时候可以定义一个数组用来存放key信息。存放和删除的时候只需要遍历数组就可以。
- 遍历JSON,获取key,value再重新put
4.JSON遍历
- 定义一个工具类,获取key和value
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
Object o = entry.getValue();
if(o instanceof String) {
System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
} else {
jsonLoop(o);
}
}
}
if(object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for(int i = 0; i < jsonArray.size(); i ++) {
jsonLoop(jsonArray.get(i));
}
}
- JSONArray遍历的方式有很多种
- for
for(int i = 0; i < jsonArray.size(); i++){ JSONObject json = jsonArray.getJSONObject(i); }
- foreach
jsonArray.forEach(o -> { if (o instanceof JSONObject) { JSONObject json = (JSONObject) o; }
- Iterator
JSONObject jsonObject = new JSONObject(jsonString); Iterator iterator = jsonObject.keys(); while(iterator.hasNext()){ key = (String) iterator.next(); value = jsonObject.getString(key); }
- for
5.JSONPath
另外向大家推荐一个非常好用的工具:JSONPath。
JSONPath是一种简单的方法来提取给定JSON的部分内容,使用方式类似于正则表达式。 GitHub地址: github.com/json-path/J…
简单描述下使用方法已经自己使用的案例 pom文件依赖:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
JsonPath表达式总是以与XPath表达式结合使用XML文档相同的方式引用JSON结构。
JsonPath中的“根成员对象”始终称为$,无论是对象还是数组。
JsonPath表达式可以使用点表示法。
这里有个表格,说明JSONPath语法元素和对应XPath元素的对比。
官方案例: 详细大家还是参照官方解说。 下面是我写的案例:
JSONArray jsonArray = JSONPath.read("$.ePrint.common..label");
需要注意的是这里的JSONArray是JSONPath的,所以导包是:net.minidev.json.JSONPath
JSON格式不会变,所以可以转换为alibaba的JSONArray:
com.alibaba.fastjson.JSONArray jsonArr = JSON.parse(jsonArray.toString());
这里要注意一点也是我踩过的坑:如果获取一个JSONObject下有多个同名的JSONArray,那么返回的[]也是多个。要先遍历获取到的数据,在取其中的一个JSON块。
感谢各位的观看,如果有不对的地方或者是好的建议,还请各位大佬指教。后期如果用到其他的JSON相关的也会更新文章。