有些第三方接口返回的数据结构是xml不是json,而我们后端一般都是存储json数据的;
xml转map工具类,懒得写,以后用到直接copy;
package com.yfq360.yfq.util;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by lv617
*/
public class CollectionUtils {
private static Pattern KEY_PATTERN = Pattern.compile("<([\\s\\S]+?)>([\\s\\S]+?)</\\1>");
private static Pattern VALUE_PATTERN = Pattern.compile("^<!\\[CDATA\\[(.+?)\\]\\]>$");
public static <T> T getFirst(Collection<T> collection){
if(collection == null) {
return null;
}
return collection.size() == 0 ? null : collection.iterator().next();
}
public static TreeMap<String, Object> xml2TreeMap(String xml) {
TreeMap<String, Object> map = new TreeMap<>();
Matcher matcher = KEY_PATTERN.matcher(xml);
while (matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
Matcher m2 = VALUE_PATTERN.matcher(value);
if (m2.find()) {
value = m2.group(1);
} else if (value.contains("</")) {
map.put(key, xml2TreeMap(value));
continue;
}
map.put(key, value);
}
return map;
}
public static boolean isEmpty(Collection collection){
return collection == null || collection.isEmpty();
}
public static boolean isNotEmpty(Collection collection){
return !isEmpty(collection);
}
public static boolean isEmpty(Map map){
return map == null || map.isEmpty();
}
public static boolean isNotEmpty(Map map){
return !isEmpty(map);
}
}