package com.goldpac.ocs.common.datahandlingservice.common.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
/**
* Created by chenyuzhi on 17-8-12.
*/
public class JsonParseUtil {
public static String checkFormat(String str){
String _str = str.trim();
if(_str.startsWith("[") && _str.endsWith("]")){
return _str.substring(1,_str.length()-1);
}
return _str;
}
/**
* 打印Map中的数据
* @param map
*/
public static Iterator<Map.Entry<String, Object>> printJsonMap(Map map){
Set entrySet = map.entrySet();
Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
//最外层提取
// while(it.hasNext()){
// Map.Entry<String, Object> e = it.next();
// System.out.println("Key 值:"+e.getKey()+" Value 值:"+e.getValue());
// }
return it;
}
/**
* JSON 类型的字符串转换成 Map
*/
public static void parseJSON2Map(Map jsonMap,String jsonStr,String parentKey){
//字符串转换成JSON对象
JSONObject json = JSONObject.parseObject(jsonStr);
//最外层JSON解析
for(Object k : json.keySet()){
//JSONObject 实际上相当于一个Map集合,所以我们可以通过Key值获取Value
Object v = json.get(k);
//构造一个包含上层keyName的完整keyName
String fullKey = (null == parentKey || parentKey.trim().equals("") ? k.toString() : parentKey + "." + k);
if(v instanceof JSONArray){
//如果内层还是数组的话,继续解析
Iterator it = ((JSONArray) v).iterator();
while(it.hasNext()){
JSONObject json2 = (JSONObject)it.next();
parseJSON2Map(jsonMap,json2.toString(),fullKey);
}
} else if(isNested(v)){
parseJSON2Map(jsonMap,v.toString(),fullKey);
}
else{
jsonMap.put(fullKey, v);
}
}
}
public static boolean isNested(Object jsonObj){
return jsonObj.toString().contains("{");
}
public static void println(Object str){
System.out.println(str);
}
}
package com.goldpac.ocs.common.datahandlingservice.mqtt;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static com.goldpac.ocs.common.datahandlingservice.common.util.JsonParseUtil.checkFormat;
import static com.goldpac.ocs.common.datahandlingservice.common.util.JsonParseUtil.parseJSON2Map;
import static com.goldpac.ocs.common.datahandlingservice.common.util.JsonParseUtil.printJsonMap;
public class test {
public static void main(String[] args) {
test test = new test();
test.test();
}
public void test(){
//JSON类型的字符串
String strJson = "{a:1,b:2,c:3,d:[{a1:11,a2:22,a3:33},{a1:{a2:222,a3:333}}]}";
// GateWayDataVo strategy = JSON.parseObject(strJson, GateWayDataVo.class);
// String dl = strategy.getB().getDvl().get(0).getDl();
Map jsonMap = new HashMap();
parseJSON2Map(jsonMap,checkFormat(strJson),null);
Iterator<Map.Entry<String, Object>> entryIterator = printJsonMap(jsonMap);
while(entryIterator.hasNext()){
Map.Entry<String, Object> e = entryIterator.next();
System.out.println("Key 值:"+e.getKey()+" Value 值:"+e.getValue());
}
}
}
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>