各种解析(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 parseJSON(String msg) {
Map resultMap = Maps.newHashMap();
return parseJSON2Map(msg, resultMap);
}

/**
* 将json串解析为MAP(支持多层嵌套)
*
* @param msg
* @return
*/
public static Map parseJSONS(String msg,String name) {
Map resultMap = Maps.newHashMap();
List list=Lists.newArrayList();
return parseJSON2Map(msg, resultMap,name,list);
}


/**
* 将拼接的字符串解析为map
*
* @param customizeParams
* @param linkSymbol
* @return
*/
public static Map parse2LinkString(String customizeParams, String linkSymbol) {
linkSymbol = S.isBlank(linkSymbol) ? connector : linkSymbol;
Map 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 parseXML(String msg) {
Map resultMap = Maps.newHashMap();
return doXMLParse(msg, resultMap);
}

private static Map doXMLParse(String strXml, Map 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 list = root.getChildren();
Iterator iter = list.iterator();
while (iter.hasNext()) {
Element element = (Element) iter.next();
String k = element.getName();
String v = "";
List children = element.getChildren();
if (children.isEmpty()) {
v = element.getTextNormalize();
result.put(k, v);
} else {
getChildrenText(children, result);
}
}
return result;
}

public static void getChildrenText(List children, Map 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 list = e.getChildren();
result.put(name, value);
if (!list.isEmpty()) {
ParseUtil.getChildrenText(list, result);
}
}
}
}

public static Map parseJson(String configJson) {
if(S.isBlank(configJson))
return new HashMap<>();
return JSONObject.parseObject(configJson, new TypeReference>() {
}.getType());
}

/**
* 将复杂json解析为扁平的map格式
* @param jsonStr json格式字符串
* @param map 需要存入的map
* @param jsonStr 如果遇到name名则不继续向下解析
* @return
*/
private static Map parseJSON2Map(String jsonStr, Map 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 list=(List)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 parseJSON2Map(String jsonStr, Map map,String name,List 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 list=(List)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 map=Maps.newHashMap();
map.put("query", value);
List list=new ArrayList();
list.add(key);
map.put("fields", list);

Map mapQueryStr=Maps.newHashMap();
mapQueryStr.put("query_string", map);

Map 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 maps = (Map)JSON.parse(str);
Map mapo=Maps.newHashMap();
if(!maps.isEmpty()){
Map map1=Maps.newHashMap();
List list1=Lists.newArrayList();
Map 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 data) {
StringBuffer sb = new StringBuffer();
sb.append("");
for (String key : data.keySet()) {
String value = data.get(key);
if (S.isNumber(value)) {
sb.append("<").append(key).append(">").append(value).append("");
} else {
sb.append("<").append(key).append(">");
}
}
return sb.append("
").toString();
}

public static Map parseQueryShandeHashMap(String customizeParams, String linkSymbol) {
String msg = "";
try {
msg = java.net.URLDecoder.decode(customizeParams, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
Map 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 bodyMap = (Map) JSON.parse(body.toString());
for (String key : bodyMap.keySet()) {
mapPara.put(key, bodyMap.get(key));
}

Object head = jo.get("head");
Map headMap = (Map) JSON.parse(head.toString());
for (String key : headMap.keySet()) {
mapPara.put(key, headMap.get(key));
}
}
return mapPara;
}

}

转载于:https://www.cnblogs.com/duoduo264/p/9524647.html

你可能感兴趣的:(各种解析(json解析map,xml解析map))