이 기사는 XML 문서를 JSON 형식 데이터로 변환하는 Java의 예를 소개합니다. 그것은 당신과 공유됩니다. 세부 사항은 다음과 같습니다.
기능
XML 문서를 JSON 형식 데이터로 변환하십시오
설명
종속성 패키지 :
1. JDOM-2.0.2.jar : XML 구문 분석 툴킷;
2. Fastjson-1.1.36.jar : Alibaba가 개발 한 고성능 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.ioexcement; java.util.linkedlist; import java.util.list;/*** 2015/5/19에 [email protected]에 의해 생성되었습니다. */public class xmlutil {public static jsonobject xml2json (byte [] xml)은 jdomexception, ioexception {jsonobject json = new jsonobject (); 입력 스트림은 = 새로운 BytearRayinputStream (XML); saxbuilder sb = new SaxBuilder (); org.jdom2.document doc = sb.build (is); 요소 root = doc.getRootElement (); json.put (root.getName (), 반복 (root)); json 리턴; } private static jsonobject iteralelement (요소 요소) {list node = element.getchildren (); 요소 et = null; jsonobject obj = new jsonobject (); 목록 목록 = null; for (int i = 0; i <node.size (); i ++) {list = new LinkedList (); et = (요소) node.get (i); if (et.getTextTrim (). Equals ( "")) {if (et.getChildren (). size () == 0) 계속; if (obj.containskey (et.getName ())) {list = (list) obj.get (et.getName ()); } list.add (iterateElement (et)); obj.put (et.getname (), list); } else {if (obj.containskey (et.getName ())) {list = (list) obj.get (et.getName ()); } list.add (et.getTextTrim ()); obj.put (et.getname (), list); }} return obj; } public static void main (string [] args)은 jdomexception, ioexception {string xml = "<? xml 버전 =/"1.0/"1.0/"encoding =/"utf-8/"?> <mobaoaccount messagetype =/"usermobilepay/" PlatformId =/"b2ctest/"> <orderno> m20150521084825 </orderno> <stradeamt> 5000.00 </tradeamt> <coundre> 0.5 </commission> <userid> zhuxiaolong </userid> <merchid> zhuxiolong1 </merchid> <tradetype> 0 <custparam> 0 <custparam> <notifyurl> http://mobaopay.com/callback.do </notifyurl> <stradesummary> 주문 </tradesummary> </mobaoaccount> "; jsonobject json = xml2json (xml.getBytes ()); System.out.println (json.tojsonstring ()); }}
실행 결과
XML 원본 텍스트 :
<? xml version = "1.0"alcoding = "utf-8"?> <mobaoaccount messagetype = "usermobilepay"platformid = "b2ctest"> <orderno> m20150521084825 </orderno> <sarteamt> 5000.00 </tradeamt> 0.5 <userid> <userid> xiAolong. <merchid> xiaolong1 </merchid> <thradetype> 0 </tradetype> <custparam> 123 </custparam> <notifyurl> http://mobaopay.com/callback.do </notifyurl> <stradesummary> order </tradesummary> </mobaoaccount>
변환 된 JSON 형식 데이터
{ "mobaoaccount": { "Commission": [ "0.5"], "custparam": [ "123"], "Merchid": [ "zhuxiaolong1"], "notifyurl": [ "http://mobaopay.com/callback.do"], "orderno": [ "M20150511084825" " "5000.00"], "tradesummary": [ "Order"], "userId": [ "ZhuxiaOlong"], "Tradetype": [ "0"]}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.