各類解析(json解析map,xml解析map)

package com.pay.paydemo.utils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.TypeReference;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.util.*;public class ParseUtil {   private static final Logger logger = LoggerFactory.getLogger(ParseUtil.class);   private static String charset = "UTF-8";   private static String connector = "&";   /**    * 將json串解析爲MAP(支持多層嵌套)    *     * @param msg    * @return    */   public static Map<String, Object> parseJSON(String msg) {      Map<String, Object> resultMap = Maps.newHashMap();      return parseJSON2Map(msg, resultMap);   }      /**    * 將json串解析爲MAP(支持多層嵌套)    *     * @param msg    * @return    */   public static Map<String, Object> parseJSONS(String msg,String name) {      Map<String, Object> resultMap = Maps.newHashMap();      List<Object> list=Lists.newArrayList();      return parseJSON2Map(msg, resultMap,name,list);   }   /**    * 將拼接的字符串解析爲map    *     * @param customizeParams    * @param linkSymbol    * @return    */   public static Map<String, Object> parse2LinkString(String customizeParams, String linkSymbol) {      linkSymbol = S.isBlank(linkSymbol) ? connector : linkSymbol;      Map<String, Object> mapPara = Maps.newHashMap();      if (!S.isBlank(customizeParams)) {         String[] a = customizeParams.split(linkSymbol);         for (String b : a) {            if (!S.isBlank(b) && b.contains("=")) {               String key = b.substring(0, b.indexOf("="));               String value = b.substring(b.indexOf("=") + 1, b.length());               mapPara.put(key, value);            }         }      }      return mapPara;   }   /**    * XML解析爲MAP    *     * @param msg    * @return    */   public static Map<String, Object> parseXML(String msg) {      Map<String, Object> resultMap = Maps.newHashMap();      return doXMLParse(msg, resultMap);   }   private static Map<String, Object> doXMLParse(String strXml, Map<String, Object> result) {      strXml = strXml.replaceFirst("encoding=\".*\"", "encoding=\"" + charset + "\"");      if (null == strXml || "".equals(strXml)) {         return null;      }      InputStream in = null;      try {         in = new ByteArrayInputStream(strXml.getBytes(charset));      } catch (UnsupportedEncodingException e) {         e.printStackTrace();         return null;      }      SAXBuilder builder = new SAXBuilder();      Document doc = null;      try {         doc = builder.build(in);      } catch (JDOMException e) {         return null;      } catch (IOException e) {         return null;      }      Element root = doc.getRootElement();      List<String> list = root.getChildren();      Iterator iter = list.iterator();      while (iter.hasNext()) {         Element element = (Element) iter.next();         String k = element.getName();         String v = "";         List<String> children = element.getChildren();         if (children.isEmpty()) {            v = element.getTextNormalize();            result.put(k, v);         } else {            getChildrenText(children, result);         }      }      return result;   }   public static void getChildrenText(List<String> children, Map<String, Object> result) {      if (!children.isEmpty()) {         Iterator it = children.iterator();         while (it.hasNext()) {            Element e = (Element) it.next();            String name = e.getName();            String value = e.getTextNormalize();            List<String> list = e.getChildren();            result.put(name, value);            if (!list.isEmpty()) {               ParseUtil.getChildrenText(list, result);            }         }      }   }   public static Map<String, String> parseJson(String configJson) {      if(S.isBlank(configJson))         return new HashMap<>();      return JSONObject.parseObject(configJson, new TypeReference<Map<String, String>>() {      }.getType());   }      /**    * 將複雜json解析爲扁平的map格式   * @param jsonStr json格式字符串   * @param map 須要存入的map   * @param jsonStr 若是遇到name名則不繼續向下解析   * @return    */   private static Map<String, Object> parseJSON2Map(String jsonStr, Map<String, Object> map) {      // 最外層解析      JSONObject json = JSONObject.parseObject(jsonStr);      for (Object k : json.keySet()) {         Object v = json.get(k);            // 若是內層仍是數組的話,繼續解析            if (v instanceof JSONObject) {               JSONObject it = JSONObject.parseObject(String.valueOf(v));               parseJSON2Map(String.valueOf(it), map);            }else if(v instanceof List){               List<Object> list=(List<Object>)v;               if(null != list && list.size()>0){                  for(Object oj:list){                     parseJSON2Map(String.valueOf(oj), map);                  }               }                           } else {               map.put(k.toString(), v);            }         }               return map;   }      private static Map<String, Object> parseJSON2Map(String jsonStr, Map<String, Object> map,String name,List<Object> listResult) {      // 最外層解析      JSONObject json = JSONObject.parseObject(jsonStr);      for (Object k : json.keySet()) {         Object v = json.get(k);         if(!k.equals(name)){            // 若是內層仍是數組的話,繼續解析            if (v instanceof JSONObject) {               JSONObject it = JSONObject.parseObject(String.valueOf(v));               parseJSON2Map(String.valueOf(it), map,name,listResult);            }else if(v instanceof List){               List<Object> list=(List<Object>)v;               if(null != list && list.size()>0){                  for(Object oj:list){                     parseJSON2Map(String.valueOf(oj), map,name,listResult);                  }               }                           } else {               map.put(k.toString(), v);            }         }else{            listResult.add(v);            continue;         }      }      if(null != listResult && listResult.size()>0){         map.put(name, listResult);      }else{         map.put(name, null);      }            return map;   }      public static void main(String[] args){      logCollect("channelHookId","9c0a118a-ed59-4c88-98d0-081a21f35c1f");   }      private static String logCollect(String key,String value){      Map<String,Object> map=Maps.newHashMap();      map.put("query", value);      List<String> list=new ArrayList<String>();      list.add(key);      map.put("fields", list);            Map<String,Object> mapQueryStr=Maps.newHashMap();      mapQueryStr.put("query_string", map);            Map<String,Object> mapParam=Maps.newHashMap();      mapParam.put("query", mapQueryStr);      String paramer=JSONObject.toJSONString(mapParam);      String str="";      try {         //2018.04.18/_search                  String path="http://127.0.0.1:9200/backend-"+Dttm.formatDateStr(new Date().getTime(), Dttm.FORMAT_DATE3)+"/_search";          str=HttpClientManager.httpPost(path, paramer, null);          System.out.println(str);      } catch (IOException e) {         logger.error("billRequestMessage>>http請求 失敗:",e);      }      Map<String,Object> maps = (Map)JSON.parse(str);        Map<String,Object> mapo=Maps.newHashMap();      if(!maps.isEmpty()){         Map map1=Maps.newHashMap();         List list1=Lists.newArrayList();         Map<String,Object> resultMap=ParseUtil.parseJSON2Map(str,map1,"_source",list1);         Object object=resultMap.get("_source");         System.out.println("object:"+object);          mapo = (Map)JSON.parse(String.valueOf(object));           String csTimestamp=String.valueOf(mapo.remove("@timestamp"));         mapo.put("cs_timestamp", Dttm.UTCStringtODefaultString(csTimestamp));         mapo.remove("@version");      }      return JSONObject.toJSONString(mapo);   }       public static String toPostXMLData(Map<String, String> data) {           StringBuffer sb = new StringBuffer();           sb.append("<xml>");           for (String key : data.keySet()) {               String value = data.get(key);               if (S.isNumber(value)) {                   sb.append("<").append(key).append(">").append(value).append("</").append(key).append(">");               } else {                   sb.append("<").append(key).append("><![CDATA[").append(value).append("]]></").append(key).append(">");               }           }           return sb.append("</xml>").toString();       }        public static Map<String, Object> parseQueryShandeHashMap(String customizeParams, String linkSymbol) {           String msg = "";           try {               msg = java.net.URLDecoder.decode(customizeParams, "UTF-8");           } catch (UnsupportedEncodingException e1) {               e1.printStackTrace();           }           Map<String, Object> mapPara = new HashMap<>();           if (!S.isBlank(msg)) {               String[] a = msg.split(linkSymbol);               for (String b : a) {                   if (!S.isBlank(b) && b.contains("=")) {                       String key = b.substring(0, b.indexOf("="));                       String value = b.substring(b.indexOf("=") + 1, b.length());                       try {                           mapPara.put(key, java.net.URLDecoder.decode(value, "UTF-8"));                       } catch (UnsupportedEncodingException e) {                           // TODO Auto-generated catch block                           e.printStackTrace();                       }                   }               }           }           String data = mapPara.get("data").toString();           if (!S.isBlank(data)) {               JSONObject jo = JSONObject.parseObject(data);               Object body = jo.get("body");               Map<String, String> bodyMap = (Map<String, String>) JSON.parse(body.toString());               for (String key : bodyMap.keySet()) {                   mapPara.put(key, bodyMap.get(key));               }               Object head = jo.get("head");               Map<String, String> headMap = (Map<String, String>) JSON.parse(head.toString());               for (String key : headMap.keySet()) {                   mapPara.put(key, headMap.get(key));               }           }           return mapPara;       }}
相關文章
相關標籤/搜索