主要用到dom4j和json的jar包
1.Map转换为xml
2.xml转为map
3.jsonString变为map
4.json对象转为map
5.按指定字符分割
6.把json数组转换为map
public class CommonUtil {
/**
* 请求Map转换为xml
* */
public String converterXml(Map<String, String> dataMap) {
// TODO Auto-generated method stub
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
strBuilder.append("<data_content>");
Set<String> objSet = dataMap.keySet();
for (String key : objSet) {
if (key == null) {
continue;
}
strBuilder.append("<").append(key.toString()).append(">");
Object value = dataMap.get(key);
strBuilder.append(value.toString());
strBuilder.append("</" + key.toString() + ">");
}
strBuilder.append("</data_content>");
return strBuilder.toString();
}
/**
* 响应xml转为map
* */
public Map<String, String> xmlToMap(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
// TODO Auto-generated catch block
}
Element node = doc.getRootElement();
Map<String, String> reponseMap = new HashMap<String, String>();
@SuppressWarnings("unchecked")
List<Element> elements = node.elements();
for (Element el : elements) {
reponseMap.put(el.getName(), el.getText());
}
return reponseMap;
}
/**
* jsonString变为map
* */
public static Map<String, String[]> parseJsonToRequestMap(String json)
throws JSONException {
JSONObject jsonObject = new JSONObject(json);
Map<String, String[]> requestMap = new HashMap<String, String[]>();
Iterator<String> it = jsonObject.keys();
// 遍历jsonObject数据,添加到Map对象
while (it.hasNext()) {
String key = it.next();
Object obj = jsonObject.opt(key);
String value = null;
if (obj != null)
value = obj.toString();
String[] values = new String[1];
values[0] = value;
requestMap.put(key, values);
}
return requestMap;
}
/**
* json变为map
* */
@SuppressWarnings("unchecked")
public static Map<String, String> parseJsonToMap(JSONObject jsonObject)
throws JSONException {
Map<String, String> requestMap = new HashMap<String, String>();
Iterator<String> it = jsonObject.keys();
// 遍历jsonObject数据,添加到Map对象
while (it.hasNext()) {
String key = it.next();
Object obj = jsonObject.opt(key);
if (obj != null)
requestMap.put(key, obj.toString());
}
return requestMap;
}
/**
* map变为jsonString
* */
public static String toJSONString(Map<String, ?> dataMap) {
JSONObject js = new JSONObject(dataMap);
return js.toString();
}
/**
* 按指定字符分割
* */
public static String[] split(String result) {
StringTokenizer splitStr = new StringTokenizer(result, "\\|");
String[] resultString = new String[7];
int i = 0;
while (splitStr.hasMoreElements()) {
resultString[i] = (String) splitStr.nextElement();
i++;
}
return resultString;
}
/**
* 把一个json数组[{},{}]转为map
* */
public Map<String, String> changeJsonAarryToMap(String jsonArray) {
Map<String, String> strMap = null;
try {
JSONArray array = new JSONArray(jsonArray);
strMap = parseJsonToMap(array.getJSONObject(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strMap;}}