比较仓促,持续优化
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
*解析SON
*/
public class JSONUtil {
private JSONObject object;
private Map<String,Object> map = new HashMap();
public JSONUtil(String json){
this.object = JSON.parseObject(json);
}
public JSONUtil(){ }
public Map getJsonMap (){
return jsonLoop(this.object,"");
}
private Map jsonLoop(Object object, String key) {
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
String key2 = "";
if(key.equals("")){
key2 = entry.getKey();
}else {
key2 = key + "." + entry.getKey();
}
Object o = entry.getValue();
if(judgeObject(o)) {
map.put(key2,entry.getValue());
} else {
this.jsonLoop(o,key2);
}
}
}else {
map.put(key,object);
}
if(object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for(int i = 0; i < jsonArray.size(); i ++) {
if(judgeObject(jsonArray.get(i))){
map.put(key,object);
//注释后遍历数组
//break;
}
this.jsonLoop(jsonArray.get(i),key+"["+i+"]");
}
}
return map;
}
private boolean judgeObject(Object o){
boolean b = false;
try {
if(!(o instanceof JSONObject || o instanceof JSONArray)){
b = true;
}
}catch (Exception e){
}
return b;
}
public static void main(String[] args) {
//JSON格式接口地址
//String url = "";
//RestTemplate restTpl = RestTemplateUtil.restTemplate();
//String restStr = restTpl.getForObject(url,String.class).trim();
String restStr = "{\"result\":{\"data\":\"123\",\"array\":[4,5,6]},\"status\":\"ok\"}";
JSONUtil jsonUtil = new JSONUtil(reststr);
Map<String,String> map = jsonUtil.getJsonMap();
System.out.println(JSON.toJSONString(map.get("result.data")));// "123"
System.out.println(JSON.toJSONString(map.get("status")));//"ok"
System.out.println(JSON.toJSONString(map.get("result.array")));[4,5,6]
System.out.println(JSON.toJSONString(map.get("result.array[0]")));4
}
}