標籤:
package com.matol.utils;import java.io.InputStream;import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Properties;import org.codehaus.jackson.map.ObjectMapper;/** * 通用多層json遞迴解析。主要是在沒有Object對象,或者是極度複雜的多級嵌套json,情況下可以以類的方式,直接擷取想要的結果。 * 支援String、Map、ArrayList、ArrayMap四種返回對象的資料擷取 * 使用方式:根據json層級關係直接使用: 基節點.子節點.孫節點 * @author ww */public class JsonUtil {private static String jsonStr = "{\"api\":\"2.1\",\"message\":[\"產品\",\"tokken\"],\"request\":{\"ptype\":\"JK\",\"tokken\":\"A#daDSFkiwi239sdls#dsd\"},\"response\":{\"status\":{\"statusCode\":\"500\",\"statusMessage\":[\"產品類型錯誤\",\"tokken失效\"]},\"page\":{\"pageSize\":\"100\",\"pageIndex\":\"1\"},\"data\":{\"ptitle\":\"all product lists\",\"sDate\":\"2014-12-01\",\"eDate\":\"2016-12-01\",\"productList\":[{\"pid\":\"RA001\",\"pname\":\"產品1\"},{\"pid\":\"RA002\",\"pname\":\"產品2\"}]}},\"args\":[{\"tit\":\"RA001\",\"val\":\"產品1\"},{\"tit\":\"RA002\",\"val\":\"產品2\"}]}";private static ObjectMapper mapper = new ObjectMapper();public static void main(String[] args) throws Exception {//測試通過json擷取Object對象//Object obj = getObjectByJson(jsonStr,"response.data.ptitle",TypeEnum.string); //層級遞迴String//System.out.println("API:"+obj.toString());//Object obj = getObjectByJson(jsonStr,"response.page",TypeEnum.map); //層級遞迴Map//System.out.println("API:"+obj.toString()+((Map)obj).get("pageSize"));//測試Objectz轉json/*Map mapPars = new HashMap();mapPars.put("agentCode", "SH0001");mapPars.put("date", "2014-01-10");mapPars.put("url", "http://www.map.com/maps.jsp?tag=2");Map mapArgs = new HashMap();mapArgs.put("query", mapPars);Map maps = new HashMap();maps.put("request", mapArgs);maps.put("date", "2014-10-10");System.out.println(getObjectByJson(maps));*///測試json層級遞迴顯示效果Map maps = mapper.readValue(jsonStr, Map.class);viewJsonTree(maps);}/** 複雜嵌套Map轉Json */public static String getObjectByJson(Object obj){String str = "";try {str = mapper.writeValueAsString(obj);} catch (Exception e) {System.out.println("###[Error] getObjectToJson() "+e.getMessage());}return str;}/** 複雜嵌套Json層級展示 */public static Object viewJsonTree(Object m){if(m == null){ System.out.println("over...");return false;}try {Map mp = null;List ls = null;if(m instanceof Map || m instanceof LinkedHashMap){mp = (LinkedHashMap)m;for(Iterator ite = mp.entrySet().iterator(); ite.hasNext();){ Map.Entry e = (Map.Entry) ite.next(); if(e.getValue() instanceof String){System.out.println("[String]"+e.getKey()+" | " + e.getValue());}else if(e.getValue() instanceof LinkedHashMap){System.out.println("{Map}"+ e.getKey()+" | "+e.getValue());viewJsonTree((LinkedHashMap)e.getValue());}else if(e.getValue() instanceof ArrayList){System.out.println("[Array]"+ e.getKey()+" | "+e.getValue());viewJsonTree((ArrayList)e.getValue());}} }if(m instanceof List || m instanceof ArrayList){ls = (ArrayList)m;for(int i=0;i<ls.size();i++){if(ls.get(i) instanceof LinkedHashMap){viewJsonTree((LinkedHashMap)ls.get(i));}else if(ls.get(i) instanceof ArrayList){viewJsonTree((ArrayList)ls.get(i));}}}System.out.println();} catch (Exception e) {System.out.println("###[Error] viewJsonTree() "+e.getMessage());}return null;}private int i = 0;/** 複雜嵌套Json擷取Object資料 */public Object getObjectByJson(String jsonStr,String argsPath,TypeEnum argsType){if(argsPath == null || argsPath.equals("") || argsType == null){return null;}Object obj = null;try {Map maps = mapper.readValue(jsonStr, Map.class);//多層擷取if(argsPath.indexOf(".") >= 0){//類型自適應obj = getObject(maps,argsPath,argsType);}else{ //第一層擷取if(argsType == TypeEnum.string){obj = maps.get(argsPath).toString();}else if(argsType == TypeEnum.map){obj = (Map)maps.get(argsPath);}else if(argsType == TypeEnum.arrayList){obj = (List)maps.get(argsPath);}else if(argsType == TypeEnum.arrayMap){obj = (List<Map>)maps.get(argsPath);}}} catch (Exception e) {System.out.println("###[Error] getObjectByJson() "+e.getMessage());}i = 0;return obj;}//遞迴擷取objectprivate Object getObject(Object m,String key,TypeEnum type){if(m == null){return null;}Object o = null;Map mp = null;List ls = null;try {//對象層級遞迴遍曆解析if(m instanceof Map || m instanceof LinkedHashMap){mp = (LinkedHashMap)m;for(Iterator ite = mp.entrySet().iterator(); ite.hasNext();){ Map.Entry e = (Map.Entry) ite.next(); if(i<key.split("\\.").length && e.getKey().equals(key.split("\\.")[i])){i++;if(e.getValue() instanceof String){if(i== key.split("\\.").length){o = e.getValue();return o;}}else if(e.getValue() instanceof LinkedHashMap){if(i== key.split("\\.").length){if(type == TypeEnum.map){o = (LinkedHashMap)e.getValue();return o;}}else{o = getObject((LinkedHashMap)e.getValue(),key,type);}return o;}else if(e.getValue() instanceof ArrayList){if(i== key.split("\\.").length){if(type == TypeEnum.arrayList){o = (ArrayList)e.getValue();return o;}if(type == TypeEnum.arrayMap){o = (ArrayList<Map>)e.getValue();return o;}}else{o = getObject((ArrayList)e.getValue(),key,type);}return o;}}} }//數組層級遞迴遍曆解析if(m instanceof List || m instanceof ArrayList){ls = (ArrayList)m;for(int i=0;i<ls.size();i++){if(ls.get(i) instanceof LinkedHashMap){if(i== key.split("\\.").length){if(type == TypeEnum.map){o = (LinkedHashMap)ls.get(i);return o;}}else{o = getObject((LinkedHashMap)ls.get(i),key,type);}return o;}else if(ls.get(i) instanceof ArrayList){if(i== key.split("\\.").length){if(type == TypeEnum.arrayList){o = (ArrayList)ls.get(i);return o;}if(type == TypeEnum.arrayMap){o = (ArrayList<Map>)ls.get(i);return o;}}else{o = getObject((ArrayList)ls.get(i),key,type);}return o;}}}} catch (Exception e) {System.out.println("###[Error] getObject() "+e.getMessage());}return o;}/* * Json資料解析返回資料類型枚舉 */public enum TypeEnum{/** 單純的索引值對,通過key擷取valus */ string, /** 通過key擷取到Map對象 */ map, /** 通過key擷取到ArrayList數組 */ arrayList, /** 通過key擷取到ArrayMap數組對象 */ arrayMap; }}
通用多層json遞迴解析,根據json層級關係直接使用: 基節點.子節點.孫節點。