本文介绍了java将XML文档转换成json格式数据的示例,分享给大家,具体如下:
功能
将xml文档转换成json格式数据
说明
依赖包:
1. jdom-2.0.2.jar : xml解析工具包;
2. fastjson-1.1.36.jar : 阿里巴巴研发的高性能json工具包
程序源代码
package com.xxx.open.pay.util; import com.alibaba.fastjson.JSONObject; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; /** * Created by 1250052380@qq.com on 2015/5/19. */ public class XmlUtil { public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException { JSONObject json = new JSONObject(); InputStream is = new ByteArrayInputStream(xml); SAXBuilder sb = new SAXBuilder(); org.jdom2.Document doc = sb.build(is); Element root = doc.getRootElement(); json.put(root.getName(), iterateElement(root)); return json; } private static JSONObject iterateElement(Element element) { List node = element.getChildren(); Element et = null; JSONObject obj = new JSONObject(); List list = null; for (int i = 0; i"; JSONObject json=xml2JSON(xml.getBytes()); System.out.println(json.toJSONString()); } } M20150521084825 5000.00 0.5 zhuxiaolong zhuxiaolong1 0 123 http://mobaopay.com/callback.do 订单
执行结果
XML原文:
<&#63;xml version="1.0" encoding="utf-8" &#63;>M20150521084825 5000.00 0.5 xiaolong xiaolong1 0 123 http://mobaopay.com/callback.do 订单
转换后的json格式数据
{ "MoBaoAccount": { "Commission": [ "0.5" ], "CustParam": [ "123" ], "MerchID": [ "zhuxiaolong1" ], "NotifyUrl": [ "http://mobaopay.com/callback.do" ], "OrderNo": [ "M20150521084825" ], "TradeAmt": [ "5000.00" ], "TradeSummary": [ "订单" ], "UserID": [ "zhuxiaolong" ], "tradeType": [ "0" ] } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。