Java xml和json互相转换方法
Posted 赵广陆
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java xml和json互相转换方法相关的知识,希望对你有一定的参考价值。
目录
1 java xml转为json的方法
1.1 fastjson和jdom2进行转化
<?xml version="1.0" encoding="utf-8" ?>
<auibinsurancecallback>
<policyinfo>
<transtype>TKTS</transtype>
<eticketno>xxx</eticketno>
<flightnumber>xxx</flightnumber>
<flightdate>2019-10-16</flightdate>
<operatetime>2019-10-16 17:20:00</operatetime>
<insureno>1910161720056066735</insureno>
<agreeno>102160199</agreeno>
<policyno>
</policyno>
<policyurl>
<!--[CDATA[]]-->
</policyurl>
</policyinfo>
<returninfo>
<serialnumber>2019103015284949545354
</serialnumber>
<retruncode>0</retruncode>
<errormessage>
<!--[CDATA[xxx]]-->
</errormessage>
</returninfo>
</auibinsurancecallback>";
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 < node.size(); i++)
list = new LinkedList();
et = (Element) node.get(i);
if (et.getTextTrim().equals(""))
if (et.getChildren().size() == 0)
continue;
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;
@Test
public void xml1()
String xml = 上面贴的xml;
JSONObject json= null;
try
json = xml2JSON(xml.getBytes());
System.out.println(json.toJSONString());
catch (JDOMException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
实现效果:
"auibinsurancecallback":
"returninfo": [
"retruncode": [
"0"
],
"serialnumber": [
"2019103015284949545354"
]
],
"policyinfo": [
"operatetime": [
"2019-10-16 17:20:00"
],
"transtype": [
"TKTS"
],
"flightdate": [
"2019-10-16"
],
"insureno": [
"1910161720056066735"
],
"flightnumber": [
"xxx"
],
"agreeno": [
"102160199"
],
"eticketno": [
"xxxx"
]
]
比较丑全是list的样子,也能用
1.2 用的org.json包
在用org.json包的时候,需要把spring-boot-starter-test中的,android-json排除,要不然会报错:
java.lang.NoSuchMethodError: org.json.JSONTokener.(Ljava/io/Reader;)V
java.lang.NoSuchMethodError: org.json.JSONObject.put(Ljava/lang/String;Ljava/util/Collection;)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
实现方法简单:
org.json.JSONObject xmlJSONObj = null;
try
xmlJSONObj = XML.toJSONObject(xml);
log.debug("json:" + xmlJSONObj.toString() );
catch (JSONException e)
e.printStackTrace();
实现效果:
"auibinsurancecallback":
"returninfo":
"errormessage": "",
"retruncode": 0,
"serialnumber": 2.0191030152849496e+21
,
"policyinfo":
"policyurl": "",
"operatetime": "2019-10-16 17:20:00",
"transtype": "TKTS",
"flightdate": "2019-10-16",
"insureno": 1910161720056066800,
"flightnumber": "xxx",
"agreeno": 102160199,
"policyno": "",
"eticketno": xxx
2 java json格式转xml格式
2.1 使用 jdom 进行转换
描述:
xml转json org.jdom
用 dom 提取节点 转成map
json 转 xml com.alibaba.fastjson.JSONObject
需要引入 jdom 1.x 版本:
<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1.3</version>
</dependency>
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonToXml
public static void main(String[] args) throws Exception
//请注意使用正常的xml
//xml->json
// String jsonStr = xmlToJson("D:\\\\NewFile.xml", null);
// System.out.println(jsonStr);
//json->xml
String xmlstr = jsonToXml("\\"b_content\\":\\"sdata\\":\\"Ps/DPJnZZPN6QQJQodY3+hK6PWCF3/2oi3DJPnFEXgKDrXX5rHT7q/I0nQPAruuBbQRfErnenQNvPpbf/lXl690qtye0/ZEuDs0ByFdFAGffQalB+Ij3lLUMDPz=\\",\\"userobj\\":\\"uid\\":\\"ma000\\",\\"realtype\\":\\"DC\\",\\"cn\\":\\"法人用户2\\",\\"tokenid\\":\\"\\",\\"usertype\\":\\"2\\",\\"link_person_name\\":\\"联系人2\\",\\"isreal\\":\\"true\\",\\"telephonenumber\\":\\"13*******21\\",\\"mail\\":\\"ceshi@123.com\\",\\"idcardtype\\":\\"10\\",\\"createtime\\":\\"20150618191221\\",\\"extproperties\\":[\\"address=广东省广州市天河区天河北路XXX号\\",\\"legal_code=440***********033\\",\\"ent_type=-1\\",\\"link_person_code=350************14\\",\\"origin=gdbs\\",\\"card_type_two_num=-1\\",\\"cert_ca=-1\\",\\"accout_type=2\\",\\"account_uid=2\\",\\"comm_code=-1\\",\\"unit_type=-1\\",\\"legal_id_type=10\\",\\"landline=-1\\",\\"tax_code=-1\\",\\"cert_notafter=-1\\",\\"card_type_one_num=-1\\",\\"local_user=-1\\",\\"legal_person=郑**\\",\\"link_person_type=10\\",\\"card_type_three=-1\\",\\"card_type_two=-1\\",\\"card_type_three_num=-1\\",\\"cert_data=-1\\",\\"area=guangzhou\\",\\"uversion=3.0\\",\\"cert_notbefore=-1\\",\\"card_type_one=-1\\",\\"user_typeext=2\\"],\\"idcardnumber\\":\\"11***************23\\",\\"useridcode\\":\\"38c97fa1ee2e43d4a664cffc4554cde4\\",\\"creditable_level_of_account_way\\":\\"L2@YSS@2088******653||L0@IDV@44088******75||L3@GW@44088******75\\",\\"creditable_level_of_account\\":\\"L3\\",\\"pareobj\\":\\"uid\\":\\"mayintao\\",\\"realtype\\":\\"DC\\",\\"cn\\":\\"单位用户2\\",\\"tokenid\\":\\"\\",\\"usertype\\":\\"2\\",\\"link_person_name\\":\\"联系人2\\",\\"isreal\\":\\"true\\",\\"telephonenumber\\":\\"13*******21\\",\\"mail\\":\\"ceshi@123.com\\",\\"idcardtype\\":\\"50\\",\\"createtime\\":\\"20150618191221\\",\\"extproperties\\":[\\"address=广东省广州市东山区\\",\\"legal_id_type=-1\\",\\"link_person_type=-1\\",\\"legal_code=-1\\",\\"origin=gdbs\\",\\"tax_code=-1\\",\\"legal_person=-1\\",\\"area=shenzhen\\",\\"link_person_code=-1\\",\\"user_typeext=2\\",\\"uversion=1.0\\"],\\"idcardnumber\\":\\"456787654\\",\\"useridcode\\":\\"75c91fagrr2e67d4a169cfmc8735ctrf\\",\\"creditable_level_of_account_way\\":\\"L2@YSS@2088******653||L0@IDV@44088******75||L3@GW@44088******75\\",\\"creditable_level_of_account\\":\\"L3\\",\\"user_creditable_level\\":\\"creditable_level_of_account_way\\":\\"L2@YSS@2088******653||L0@IDV@44088******75||L3@GW@44088******75\\",\\"creditable_level_of_account_way_list\\":[\\"auth_time\\":\\"2018-02-28 16:45:26\\",\\"uniqueid\\":\\"***86f93fb61***\\",\\"user_name\\":\\"郭**\\",\\"auth_identification\\":\\"2088******653\\",\\"identity_level\\":\\"L2\\",\\"credential_no\\":\\"44088******75\\",\\"way_code\\":\\"YSS\\",\\"auth_time\\":null,\\"uniqueid\\":\\"***764486f93fb61212***\\",\\"user_name\\":\\"郭**\\",\\"auth_identification\\":\\"44088******75\\",\\"identity_level\\":\\"L0\\",\\"credential_no\\":\\"44088******75\\",\\"way_code\\":\\"IDV\\",\\"auth_time\\":\\"2018-02-13 17:12:31\\",\\"uniqueid\\":\\"*****764486f93fb612122*****\\",\\"user_name\\":\\"郭**\\",\\"auth_identification\\":\\"44088******75\\",\\"identity_level\\":\\"L3\\",\\"credential_no\\":\\"44088******75\\",\\"way_code\\":\\"GW\\"],\\"creditable_level_of_account\\":\\"L3\\",\\"time_stamp\\":\\"20200821\\",\\"version \\":\\"v1\\",\\"sign\\":\\"rxf0MFT7eQqYgYKWtgzNBi6mhS2tbqkPgI \\"");
System.out.println(xmlstr);
createXMLFile(formatXML(xmlstr), "测试");
/**
* xml转json字符串 注意:路径和字符串二传一另外一个传null<br>
* 方 法 名:xmlToJson <br>
* @param xmlPath xml路径(和字符串二传一,两样都传优先使用路径)
* @param xmlStr xml字符串(和路径二传一,两样都传优先使用路径)
* @return String
* @throws IOException
* @throws JDOMException
*/
@SuppressWarnings("unchecked")
public static String xmlToJson(String xmlPath,String xmlStr)
SAXBuilder sbder = new SAXBuilder();
Map<String, Object> map = new HashMap<String, Object>();
Document document;
try
if(xmlPath!=null)
//路径
document = sbder.build(new File(xmlPath));
else if(xmlStr!=null)
//xml字符
StringReader reader = new StringReader(xmlStr);
InputSource ins = new InputSource(reader);
document = sbder.build(ins);
else
return "";
//获取根节点
Element el = document.getRootElement();
List<Element> eList = el.getChildren();
Map<String, Object> rootMap = new HashMap<String, Object>();
//得到递归组装的map
rootMap = xmlToMap(eList,rootMap);
map.put(el.getName(), rootMap);
//将map转换为json 返回
return JSON.toJSONString(map);
catch (Exception e)
return "";
/**
* json转xml<br>
* 方 法 名:jsonToXml <br>
* @param json
* @return String
*/
public static String jsonToXml(String json)
try
StringBuffer buffer = new StringBuffer();
buffer.append("<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>");
buffer.append("<base>");
JSONObject jObj = JSON.parseObject(json);
jsonToXmlstr(jObj,buffer);
buffer.append("</base>");
return buffer.toString();
catch (Exception e)
e.printStackTrace();
return "";
/**
* json转str<br>
* 方 法 名:jsonToXmlstr <br>
* @param jObj
* @param buffer
* @return String
*/
public static String jsonToXmlstr(JSONObject jObj,StringBuffer buffer )
Set<Entry<String, Object>> se = jObj.entrySet();
for( Iterator<Entry<String, Object>> it = se.iterator(); it.hasNext(); )
Entry<String, Object> en = it.next();
if(en.getValue() != null && en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONObject"))
buffer.append("<"+en.getKey()+">");
JSONObject jo = jObj.getJSONObject(en.getKey());
jsonToXmlstr(jo,buffer);
buffer.append("</"+en.getKey()+">");
else if(en.getValue() != null && en.getValue().getClass().getName(以上是关于Java xml和json互相转换方法的主要内容,如果未能解决你的问题,请参考以下文章
json:JSONObject包的具体使用(JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包)
IOS开发之----NSDictionary,JSON和XML互相转换
JSON相关 JSON在线解析 JSON压缩转义工具 JSON着色工具 JSON 在线格式化工具 在线XML/JSON互相转换工具 XMLJSON在线转换