- json 數(shù)據(jù):
{
"status": 0,
"desc": "請求成功",
"data": {
"goods": [{
"id": "01",
"name": "手機",
"price": 1000,
"operaList": [{
"taskName": "已發(fā)貨",
"operTime": "2019-09-02 08:00:00"
}]
},
{
"id": "02",
"name": "電腦",
"price": 3000,
"operaList": [],
"json": {
}
}]
},
"list": [{
"taskName": "已下單",
"operTime": "2019-09-01 08:00:00"
},
{
"taskName": "已付款",
"operTime": "2019-09-01 09:15:22"
}]
}
{
"body": {
"num": 1,
"str": "aaa",
"listStr": ["a","b","c"],
"listjson": [{
"body1": {
"num": 1,
"str": "aaa",
}
},
{
"body2": {
"num": 1,
"str": "aaa",
"listjson": []
}
}]
}
}
- maven依賴:
<dependency>
<groupId>com.github.wnameless</groupId>
<artifactId>json-flattener</artifactId>
<version>0.6.0</version>
</dependency>
二 轉(zhuǎn)為map
/**
* json 扁平化,級別直接默認(rèn).隔開
*
* @param jsonStr json
*/
private static void jsonFlatten(String jsonStr) {
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Map<String, Object> map = JsonFlattener.flattenAsMap(jsonObject.toString());
//修改級別之間的分隔字符
//Map<String, Object> map2 = new JsonFlattener(jsonObject.toString()).withSeparator('/').flattenAsMap();
for (Map.Entry<String, Object> e : map.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
}
輸出
body.str = aaa
body.num = 1
body.listjson[0].body1.str = aaa
body.listjson[0].body1.num = 1
body.listjson[1].body2.str = aaa
body.listjson[1].body2.num = 1
body.listjson[1].body2.listjson = []
body.listStr[0] = a
body.listStr[1] = b
body.listStr[2] = c
完整代碼
/**
* jsonStr 扁平化為 String
*
* @param jsonStr json字符串
* @return 扁平化后的字符串
*/
public static String jsonFlattenAsStr(String jsonStr) {
return JsonFlattener.flatten(jsonStr);
}
/**
* jsonStr 扁平化為 Map
*
* @param jsonStr json字符串
* @return 扁平化后的Map對象
*/
public static Map<String, Object> jsonFlattenAsMap(String jsonStr) {
return JsonFlattener.flattenAsMap(jsonStr);
}
/**
* 反扁平化
* 將扁平化后的 str 轉(zhuǎn)為 json字符串
*
* @param flattenStr 扁平化后的字符串
* @return 立體后的json字符串
*/
public static String jsonUnFlatten(String flattenStr) {
return JsonUnflattener.unflatten(flattenStr);
}
/**
* jsonStr 扁平化為 String
* 并制定級別之間的分隔字符
*
* @param jsonStr json字符串
* @param spliter 自定義分隔符
* @return 扁平化后的字符串
*/
public static String jsonFlattenAsStr(String jsonStr, char spliter) {
return new JsonFlattener(jsonStr).withSeparator(spliter).flatten();
}
/**
* json扁平化為map 并修改分隔符
* 修改級別之間的分隔字符
*
* @param jsonStr json字符串
* @param spliter 自定義分隔符
* @return 扁平化后的Map對象
*/
public static Map<String, Object> jsonFlatten(String jsonStr, char spliter) {
return new JsonFlattener(jsonStr).withSeparator(spliter).flattenAsMap();
}
/**
* 反扁平化
* 將扁平化后的 str 轉(zhuǎn)為 json字符串
*
* @param flattenStr 扁平化后的字符串
* @param spliter 自定義分隔符
* @return j立體后的json字符串
*/
public static String jsonUnFlatten(String flattenStr, char spliter) {
return new JsonUnflattener(flattenStr).withSeparator(spliter).unflatten();
}
參考:https://www.cnblogs.com/hyl8218/p/11066500.html
項目地址:https://github.com/FasterXML/jackson