码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA 实现XML与JSON 相互转换

时间:2018-06-10 11:59:54      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:except   .net   swa   catch   stack   stream   trace   title   exce   

原文地址https://blog.csdn.net/congcong68/article/details/39029907

在工作中,经常碰到XML转为JSON或者JSON转为XML,在这过程中有时嵌套很多层,容易错误,我把实现的代码分享出来,希望对有用到的人提供借鉴。

     

   1.把XML转为JSON格式

          

[java] view plain copy
 
  1. <span style="font-size:18px;">@SuppressWarnings("rawtypes")  
  2.     public static  String xmlToJSON(String xml,int jsonType) {  
  3.         JSONObject obj = new JSONObject();  
  4.         try {  
  5.             InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));  
  6.             SAXBuilder sb = new SAXBuilder();  
  7.             Document doc = sb.build(is);  
  8.             Element root = doc.getRootElement();  
  9.             Map map=iterateElement(root);  
  10.            obj.put(root.getName(),map);  
  11.            return obj.toString();  
  12.         } catch (Exception e) {  
  13.             e.printStackTrace();  
  14.             return null;  
  15.         }  
  16.     }  
  17.   
  18.   
  19. @SuppressWarnings({ "unchecked", "rawtypes" })  
  20.     private static Map  iterateElement(Element root) {  
  21.         List childrenList = root.getChildren();  
  22.         Element element = null;  
  23.         Map map = new HashMap();  
  24.         List list = null;  
  25.         for (int i = 0; i < childrenList.size(); i++) {  
  26.             list = new ArrayList();  
  27.             element = (Element) childrenList.get(i);  
  28.             if(element.getChildren().size()>0){  
  29.                 if(root.getChildren(element.getName()).size()>1){  
  30.                     if (map.containsKey(element.getName())) {  
  31.                         list = (List) map.get(element.getName());  
  32.                     }  
  33.                     list.add(iterateElement(element));  
  34.                     map.put(element.getName(), list);  
  35.                 }else{  
  36.                     map.put(element.getName(), iterateElement(element));  
  37.                 }  
  38.             }else {  
  39.                 if(root.getChildren(element.getName()).size()>1){  
  40.                     if (map.containsKey(element.getName())) {  
  41.                         list = (List) map.get(element.getName());  
  42.                     }  
  43.                     list.add(element.getTextTrim());  
  44.                     map.put(element.getName(), list);  
  45.                 }else{  
  46.                     map.put(element.getName(), element.getTextTrim());  
  47.                 }  
  48.             }  
  49.         }  
  50.           
  51.         return map;  
  52.     }  
  53.       
  54.   
  55.   
  56.     public static void main(String[] args) throws ParseException  
  57.     {         
  58.         String xml="<ROOT>"+  
  59.         "<Status>00</Status>"+  
  60.         "<ErrorMsg></ErrorMsg>"+  
  61.         "<Data>"+  
  62.            "<Row>"+  
  63.               "<PERSONID>35020500200610000000000701355116</PERSONID>"+  
  64.               "<XM>吴聪楠</XM><SFZH>350624198908052530</SFZH>"+  
  65.            "</Row>"+  
  66.            "<Row>"+  
  67.               "<PERSONID>35020500200610000000000701355117</PERSONID>"+  
  68.               "<XM>吴聪楠2</XM><SFZH>350624198908052531</SFZH>"+  
  69.               "</Row>"+  
  70.           "</Data>"+  
  71.     "</ROOT>";  
  72.   
  73.           
  74.         String str=Xml2JsonUtil.xmlToJSON(xml,1);  
  75.       System.out.println(str);  
  76. }</span>  

原来的格式:

    <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格式

[java] view plain copy
 
  1. <span style="font-size:18px;">public static  String JsonToXml(Object json)   
  2.     {  
  3.         if(json==null){  
  4.             return null;  
  5.         }else{  
  6.          Element elements=new Element("xml");  
  7.          getXMLFromObject(json,"xml",elements);  
  8.          XMLOutputter xmlOut = new XMLOutputter();    
  9.          String res=xmlOut.outputString(elements);  
  10.          return res;  
  11.        }  
  12.     }  
  13.   
  14.   
  15. private static void getXMLFromObject(Object obj,String tag,Element parent)  
  16.     {  
  17.         if(obj==null)  
  18.             return;  
  19.         Element child;  
  20.         String eleStr;  
  21.         Object childValue;  
  22.         if(obj instanceof JSONObject)  
  23.         {  
  24.             JSONObject jsonObject=(JSONObject)obj;  
  25.             for(Object temp:jsonObject.keySet())  
  26.             {  
  27.                 eleStr=temp.toString();  
  28.                 childValue=jsonObject.get(temp);  
  29.                 child=new Element(eleStr);  
  30.                 if(childValue instanceof JSONArray)  
  31.                     getXMLFromObject(childValue,eleStr,parent,count);  
  32.                 else{  
  33.                     parent.addContent(child);  
  34.                     getXMLFromObject(childValue,eleStr,child,count);  
  35.                 }  
  36.             }  
  37.         }else if(obj instanceof JSONArray){  
  38.             JSONArray jsonArray=(JSONArray)obj;  
  39.             for(int i=0;i<jsonArray.size();i++)  
  40.             {  
  41.                 childValue=jsonArray.get(i);  
  42.                 child=new Element(tag);  
  43.                 parent.addContent(child);  
  44.                 getXMLFromObject(childValue,tag,child,count);  
  45.             }  
  46.         }else if(obj instanceof Date){  
  47.             SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  48.             parent.setText(sf.format((Date)obj));  
  49.         }else{  
  50.             parent.setText(obj.toString());  
  51.         }  
  52.     }  
  53.           
  54.   
  55. public static void main(String[] args) throws ParseException  
  56.     {  
  57.   JSONObject rootObject=new JSONObject();  
  58.        
  59.       JSONArray dataArray=new JSONArray();  
  60.       JSONObject dataObject1=new JSONObject();  
  61.       dataObject1.put("PERSONID", "35020500200610000000000701355117");  
  62.       dataObject1.put("XM", "吴聪楠");  
  63.       dataObject1.put("SFZH","350624198908052530");  
  64.       dataArray.add(dataObject1);  
  65.       JSONObject dataObject2=new JSONObject();  
  66.       dataObject2.put("PERSONID", "35020500200610000000000701355116");  
  67.       dataObject2.put("XM", "吴聪楠2");  
  68.       dataObject2.put("SFZH","350624198908052531");  
  69.       dataArray.add(dataObject2);  
  70.       
  71.       JSONObject dataRootObject=new JSONObject();  
  72.       dataRootObject.put("Row", dataArray);  
  73.       JSONObject dataObject=new JSONObject();  
  74.       dataObject.put("Status", "00");  
  75.       dataObject.put("ErrorMsg", "");  
  76.       dataObject.put("Data",dataRootObject);  
  77.       rootObject.put("ROOT", dataObject);  
  78.         
  79.       System.out.println(rootObject.toString());  
  80.       System.out.println(JsonToXml(rootObject));          
  81.           
  82.     }</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>

JAVA 实现XML与JSON 相互转换

标签:except   .net   swa   catch   stack   stream   trace   title   exce   

原文地址:https://www.cnblogs.com/111testing/p/9162240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!