Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2561339
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2012-10-29 22:55:21

java将xml转换为json的另一种方法。需要用到的类库:

请自己注意添加以上类库的依赖包。

java代码:

点击(此处)折叠或打开

  1. package com.mibridge.util;

  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.InputStream;

  5. import net.sf.json.JSON;
  6. import net.sf.json.xml.XMLSerializer;

  7. public class ConvertXMLtoJSON {
  8.     public static void main(String[] args) throws Exception {
  9.         String xml = getXMLString("soap-origin.xml");
  10.         System.out.println(xml);
  11.         XMLSerializer xmlSerializer = new XMLSerializer();
  12.         JSON json = xmlSerializer.read(xml);
  13.         System.out.println(json.toString(2));
  14.     }

  15.     private static String getXMLString(String filePath) {
  16.         StringBuffer sb = new StringBuffer();
  17.         BufferedReader br = null;
  18.         String line;
  19.         try {
  20.             br = new BufferedReader(new FileReader(filePath));
  21.             while (true) {
  22.                 line = br.readLine();
  23.                 if (line == null) {
  24.                     break;
  25.                 }
  26.                 sb.append(line + "\n");
  27.             }
  28.         } catch (Exception e) {
  29.             e.printStackTrace();
  30.         }
  31.         return sb.toString();
  32.     }

  33. }
xml文档soap-origin.xml:

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <soapenv:Envelope xmlns:soapenv="">
  3. <soapenv:Body>
  4. <ns:Response xmlns:ns="">
  5.    <ns:return>
  6.       <ns:person>
  7.          <ns:personName></ns:personName>
  8.          <ns:personAge></ns:personAge>
  9.          <ns:personAddress>
  10.             <ns:addressType>家庭住址</ns:addressType>
  11.             <ns:addressLine1>中国深圳</ns:addressLine1>
  12.          </ns:personAddress>
  13.          <ns:personAddress>
  14.             <ns:addressType>公司地址</ns:addressType>
  15.             <ns:addressLine1>荔香公园</ns:addressLine1>
  16.          </ns:personAddress>
  17.       </ns:person>
  18.    </ns:return>
  19. </ns:Response>
  20. </soapenv:Body>
  21. </soapenv:Envelope>

输出的json:

  1. {
  2.   "@xmlns:soapenv": "",
  3.   "soapenv:Body": {"ns:Response": {
  4.     "@xmlns:ns": "",
  5.     "ns:return": {"ns:person": {
  6.       "ns:personName": null,
  7.       "ns:personAge": null,
  8.       "ns:personAddress": [
  9.                 {
  10.           "ns:addressType": "家庭住址",
  11.           "ns:addressLine1": "中国深圳"
  12.         },
  13.                 {
  14.           "ns:addressType": "公司地址",
  15.           "ns:addressLine1": "荔香公园"
  16.         }
  17.       ]
  18.     }}
  19.   }}
  20. }

阅读(2176) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~