JAVA 实现XML与JSON 相互转换

1.把XML转为JSON格式

     

        

@SuppressWarnings("rawtypes")  
    public static  String xmlToJSON(String xml,int jsonType) {  
        JSONObject obj = new JSONObject();  
        try {  
            InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));  
            SAXBuilder sb = new SAXBuilder();  
            Document doc = sb.build(is);  
            Element root = doc.getRootElement();  
            Map map=iterateElement(root);  
           obj.put(root.getName(),map);  
           return obj.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
  
  
@SuppressWarnings({ "unchecked", "rawtypes" })  
    private static Map  iterateElement(Element root) {  
        List childrenList = root.getChildren();  
        Element element = null;  
        Map map = new HashMap();  
        List list = null;  
        for (int i = 0; i < childrenList.size(); i++) {  
            list = new ArrayList();  
            element = (Element) childrenList.get(i);  
            if(element.getChildren().size()>0){  
                if(root.getChildren(element.getName()).size()>1){  
                    if (map.containsKey(element.getName())) {  
                        list = (List) map.get(element.getName());  
                    }  
                    list.add(iterateElement(element));  
                    map.put(element.getName(), list);  
                }else{  
                    map.put(element.getName(), iterateElement(element));  
                }  
            }else {  
                if(root.getChildren(element.getName()).size()>1){  
                    if (map.containsKey(element.getName())) {  
                        list = (List) map.get(element.getName());  
                    }  
                    list.add(element.getTextTrim());  
                    map.put(element.getName(), list);  
                }else{  
                    map.put(element.getName(), element.getTextTrim());  
                }  
            }  
        }  
          
        return map;  
    }  
      
  
  
    public static void main(String[] args) throws ParseException  
    {         
        String xml="<ROOT>"+  
        "<Status>00</Status>"+  
        "<ErrorMsg></ErrorMsg>"+  
        "<Data>"+  
           "<Row>"+  
              "<PERSONID>35020500200610000000000701355116</PERSONID>"+  
              "<XM>吴聪楠</XM><SFZH>350624198908052530</SFZH>"+  
           "</Row>"+  
           "<Row>"+  
              "<PERSONID>35020500200610000000000701355117</PERSONID>"+  
              "<XM>吴聪楠2</XM><SFZH>350624198908052531</SFZH>"+  
              "</Row>"+  
          "</Data>"+  
    "</ROOT>";  
  
          
        String str=Xml2JsonUtil.xmlToJSON(xml,1);  
      System.out.println(str);  
}

原来的格式:

    <ROOT><Status>00</Status><ErrorMsg></ErrorMsg><Data><Row><PERSONID>35020500200610000000000701355116</PERSONID><XM>吴聪楠</XM><SFZH>350624198908052530</SFZH></Row><Row><PERSONID>35020500200610000000000701355117</PERSONID><XM>吴聪楠2</XM><SFZH>350624198908052530</SFZH></Row></Data></ROOT>

转换完的格式:

   <span style="font-size:18px;">{"ROOT":{"Data":{"Row":[{"SFZH":"350624198908052530","XM":"吴聪楠","PERSONID":"35020500200610000000000701355116"},{"SFZH":"350624198908052530","XM":"吴聪楠2","PERSONID":"35020500200610000000000701355117"}]},"Status":"00","ErrorMsg":""}}</span>

  2.JSON 转换为XML格式

    

public static  String JsonToXml(Object json)   
    {  
        if(json==null){  
            return null;  
        }else{  
         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,count);  
                else{  
                    parent.addContent(child);  
                    getXMLFromObject(childValue,eleStr,child,count);  
                }  
            }  
        }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,count);  
            }  
        }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());  
        }  
    }  
          
  
public static void main(String[] args) throws ParseException  
    {  
  JSONObject rootObject=new JSONObject();  
       
      JSONArray dataArray=new JSONArray();  
      JSONObject dataObject1=new JSONObject();  
      dataObject1.put("PERSONID", "35020500200610000000000701355117");  
      dataObject1.put("XM", "吴聪楠");  
      dataObject1.put("SFZH","350624198908052530");  
      dataArray.add(dataObject1);  
      JSONObject dataObject2=new JSONObject();  
      dataObject2.put("PERSONID", "35020500200610000000000701355116");  
      dataObject2.put("XM", "吴聪楠2");  
      dataObject2.put("SFZH","350624198908052531");  
      dataArray.add(dataObject2);  
      
      JSONObject dataRootObject=new JSONObject();  
      dataRootObject.put("Row", dataArray);  
      JSONObject dataObject=new JSONObject();  
      dataObject.put("Status", "00");  
      dataObject.put("ErrorMsg", "");  
      dataObject.put("Data",dataRootObject);  
      rootObject.put("ROOT", dataObject);  
        
      System.out.println(rootObject.toString());  
      System.out.println(JsonToXml(rootObject));          
          
    }</span>  

  原来的格式:

     

{"ROOT":{"Status":"00","ErrorMsg":"","Data":{"Row":[{"PERSONID":"35020500200610000000000701355117","XM":"吴聪楠","SFZH":"350624198908052530"},{"PERSONID":"35020500200610000000000701355116","XM":"吴聪楠2","SFZH":"350624198908052531"}]}}}

 

转换完的格式:

   

<ROOT><Status>00</Status><ErrorMsg></ErrorMsg><Data><Row><PERSONID>35020500200610000000000701355117</PERSONID><XM>吴聪楠</XM><SFZH>350624198908052530</SFZH></Row><Row><PERSONID>35020500200610000000000701355116</PERSONID><XM>吴聪楠2</XM><SFZH>350624198908052531</SFZH></Row></Data></ROOT>

相关推荐