前段时间有一个项目中有20多个比较复杂的xml和json要进行互转,在网上查找了很多案例都不理想,很多节点会无故丢失,
后来请教同事帮忙编写一个通用类解决了这个问题,希望可以帮到你!
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.json.JSONException;
import org.json.XML;
import org.json.simple.JSONArray;
import net.sf.json.JSONObject;
public class XmlAndJson {
private static Map<String,Object> getAttributes(Element element){
Map<String,Object> result = new HashMap<String,Object>();
List<Attribute> attrList = element.getAttributes();
for(Attribute attr : attrList){
result.put(attr.getName(),attr.getValue());
}
return result;
}
private static Map<String,Object> iterateElement(Element element) {
Map<String,Object> result = new HashMap<String,Object>();
if(element.getText().isEmpty() == false || element.getText().intern().equals("") == false){
result.put(element.getName(), element.getValue());
return result;
}
List<Attribute> attrList = element.getAttributes();
for(Attribute attr : attrList){
result.put(attr.getName(),attr.getValue());
}
//如果子集不为空,则迭代
List<Element> children = element.getChildren();
if(children.isEmpty() == false){
List<Map<String,Object>> childList = new ArrayList<Map<String,Object>>();
Map<String,List<Map<String,Object>>> temp = new HashMap<String,List<Map<String,Object>>>();
for(Element child : children){
if(element.getChildren(child.getName()).size() > 1){
List<Map<String,Object>> te = temp.get(child.getName());
Map<String,Object> childMap = new HashMap<String,Object>();
childMap.put(child.getName(), iterateElement(child));
if(te != null && te.isEmpty() == false){
te.add(childMap);
}else{
te = new ArrayList<Map<String,Object>>();
te.add(childMap);
temp.put(child.getName(), te);
}
}else{
if(child.getChildren().isEmpty()){
if(child.getAttributes().isEmpty() == false){
List<Attribute> cattrList = child.getAttributes();
Map<String,Object> childMap = new HashMap<String,Object>();
for(Attribute attr : cattrList){
childMap.put(attr.getName(),attr.getValue());
}
result.put(child.getName(), childMap);
}else
result.put(child.getName(), child.getValue());
}else
result.put(child.getName(), iterateElement(child));
}
}
for(String key : temp.keySet()){
List<Map<String,Object>> cList = new ArrayList<Map<String,Object>>();
for(Map<String,Object> obj : temp.get(key)){
cList.add((Map<String,Object>)obj.get(key));
}
result.put(key, cList);
}
}
return result;
}
/**
* 转换一个xml格式的字符串到json格式
*
* @param xml
* xml格式的字符串
* @return 成功返回json 格式的字符串;失败反回null
*/
public String xmlToJson(String xml) {
String json = null;
JSONObject obj = new JSONObject();
org.json.JSONObject jsonObj = null;
try {
InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
obj.put(root.getName(), iterateElement(root));
jsonObj = XML.toJSONObject(xml);
} catch (Exception e) {
e.printStackTrace();
}
return obj.toString();
}
/**
* 转换一个json格式的字符串到xml格式
*
* @param json
* json格式的字符串
* @return 成功返回xml 格式的字符串;失败反回null
*/
public String jsonToXml(String jsonstr) {
if(json==null){
return null;
}else{
JSONObject cc = new JSONObject();
JSONObject json=cc.fromObject(jsonstr);
Element elements=new Element("xml");
getXMLFromObject(json,"xml",elements);
XMLOutputter xmlOut = new XMLOutputter();
String res=xmlOut.outputString(elements);
return res;
}
}
private static void getXMLFromObject(Object obj,String tag,Element parent)
{
if(obj==null)
return;
Element child;
String eleStr;
Object childValue;
if(obj instanceof JSONObject)
{
JSONObject jsonObject=(JSONObject)obj;
for(Object temp:jsonObject.keySet())
{
eleStr=temp.toString();
childValue=jsonObject.get(temp);
child=new Element(eleStr);
if(childValue instanceof JSONArray)
getXMLFromObject(childValue,eleStr,parent );
else{
parent.addContent(child);
getXMLFromObject(childValue,eleStr,child );
}
}
}else if(obj instanceof JSONArray){
JSONArray jsonArray=(JSONArray)obj;
for(int i=0;i<jsonArray.size();i++)
{
childValue=jsonArray.get(i);
child=new Element(tag);
parent.addContent(child);
getXMLFromObject(childValue,tag,child );
}
}else if(obj instanceof Date){
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
parent.setText(sf.format((Date)obj));
}else{
parent.setText(obj.toString());
}
}
}