目录


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().equals("com.alibaba.fastjson.JSONArray")){
if (en.getKey().equals("extproperties")) {
JSONArray ja = jObj.getJSONArray(en.getKey());
Iterator<Object> it1 = ja.iterator();
List<String> list=new ArrayList<String>();
while (it1.hasNext()) {
String ob = (String) it1.next();
System.out.println(ob);
}
}else {
JSONArray jarray = jObj.getJSONArray(en.getKey());
for (int i = 0; i < jarray.size(); i++) {
buffer.append("<"+en.getKey()+">");
JSONObject jsonobject = jarray.getJSONObject(i);
jsonToXmlstr(jsonobject,buffer);
buffer.append("</"+en.getKey()+">");
}
}

}else if(en.getValue() != null && en.getValue().getClass().getName().equals("java.lang.String")){
buffer.append("<"+en.getKey()+">"+en.getValue());
buffer.append("</"+en.getKey()+">");
}else{
buffer.append("<"+en.getKey()+">"+"");
buffer.append("</"+en.getKey()+">");
}

}
return buffer.toString();
}


/**
* 节点转map<br>
* 方 法 名:xmlToMap <br>
* @param eList
* @param map
* @return Map<String,Object>
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> xmlToMap(List<Element> eList,Map<String, Object> map){
for (Element e : eList) {
Map<String, Object> eMap = new HashMap<String, Object>();
List<Element> elementList = e.getChildren();
if(elementList!=null&&elementList.size()>0){
eMap = xmlToMap(elementList,eMap);
Object obj = map.get(e.getName());
if(obj!=null){
List<Object> olist = new ArrayList<Object>();
if(obj.getClass().getName().equals("java.util.HashMap")){
olist.add(obj);
olist.add(eMap);

}else if(obj.getClass().getName().equals("java.util.ArrayList")){
olist = (List<Object>)obj;
olist.add(eMap);
}
map.put(e.getName(), olist);
}else{
map.put(e.getName(), eMap);
}
}else{
map.put(e.getName(), e.getValue());
}
}
return map;
}


/**
* 将已经格式化的xml字符串写入xml文件
* @param xmlStr
* @return
*/
public static boolean createXMLFile(String xmlStr,String xmlName){
boolean flag = false;
try {
XMLWriter output = null;
//OutputFormat format = OutputFormat.createPrettyPrint();
//format.setSuppressDeclaration(true);
// format.setEncoding("UTF-8");

//如果上面设置的xml编码类型为GBK,则应当用FileWriter来构建xml文件,否则会出现中文连码问题
/*outpt = new XMLWriter(
new FileWriter(
new File("D:/myeclipse/Workspaces/fusionChartsDemoTest/WebRoot/xml/"+xmlName+".xml")) ,
format);
*/

//如果上面设置的xml编码类型为utf-8,则应当用FileOutputStream来构建xml文件,否则还是会出现问题
output = new XMLWriter(
new FileOutputStream(
new File("D:/"+xmlName+".xml")));
output.setEscapeText(false);
output.write( xmlStr );
output.close();
return flag = true;

} catch (IOException e) {
e.printStackTrace();
return flag;
}

}

public static String formatXML(String str) throws Exception {

SAXReader reader=new SAXReader();

//创建一个串的字符输入流
StringReader in=new StringReader(str);
org.dom4j.Document doc=reader.read(in);
// 创建输出格式
OutputFormat formater=OutputFormat.createPrettyPrint();
//去掉xml文件的版本信息
//formater.setSuppressDeclaration(true);
//设置xml的输出编码
formater.setEncoding("UTF-8");
//创建输出(目标)
StringWriter out=new StringWriter();
//创建输出流
XMLWriter writer=new XMLWriter(out,formater);
//输出格式化的串到目标中,执行后。格式化后的串保存在out中。
writer.write(doc);

writer.close();

// System.out.println(out.toString());

//返回我们格式化后的结果
return out.toString();
}
}

2.2 使用 dom4j 进行转换

描述:

使用 dom4j 和
com.google.gson.*

需要引入 dom4j 1.6.1 版本和 gson:

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map.Entry;
import java.util.Set;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.google.gson.*;

public class JsonToXml2 {
private static final String STR_JSON = "{\"stakeapply\":{\"voltageLevel\":\"AC00062\",\"stakeList\":{\"stake\":[{\"stakeAssetNO\":45754745,\"otherStakeTypeRemark\":\"xxx\",\"stationId\":\"547547547547\"},{\"stakeAssetNO\":34325325322,\"otherStakeTypeRemark\":\"xxx\",\"stationId\":\"52354645462\"}]},\"otherStationTypeRemark\":\"xxx\",\"stationAddr\":\"哈哈\",\"custLists\":{\"custList\":{\"custId\":\"7547547547\",\"custPhone\":13666666666,\"contactMode\":1}},\"principalList\":{\"principal\":[{\"principalName\":121212,\"principalType\":1},{\"principalName\":12121233,\"principalType\":1}]}}}";

/**
* 将json字符串转换成xml
*
* @param json
* json字符串
* @param parentElement
* xml根节点
* @throws Exception
*/
public static Element jsonToXml(String json, Element parentElement) throws Exception {
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
Element ee = toXml(jsonObject, parentElement, null);
return ee;
}

/**
* 将json字符串转换成xml
*
* @param jsonElement
* 待解析json对象元素
* @param parentElement
* 上一层xml的dom对象
* @param name
* 父节点
*/
public static Element toXml(JsonElement jsonElement, Element parentElement, String name) {
if (jsonElement instanceof JsonArray) {
//是json数据,需继续解析
JsonArray sonJsonArray = (JsonArray)jsonElement;
for (int i = 0; i < sonJsonArray.size(); i++) {
JsonElement arrayElement = sonJsonArray.get(i);
toXml(arrayElement, parentElement, name);
}
}else if (jsonElement instanceof JsonObject) {
//说明是一个json对象字符串,需要继续解析
JsonObject sonJsonObject = (JsonObject) jsonElement;
Element currentElement = null;
if (name != null) {
currentElement = parentElement.addElement(name);
}
Set<Entry<String, JsonElement>> set = sonJsonObject.entrySet();
for (Entry<String, JsonElement> s : set) {
toXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
}
} else {
//说明是一个键值对的key,可以作为节点插入了
addAttribute(parentElement, name, jsonElement.getAsString());
}
return parentElement;
}

/**
*
* @param element 父节点
* @param name 子节点的名字
* @param value 子节点的值
*/
public static void addAttribute(Element element, String name, String value) {
//增加子节点,并为子节点赋值
Element el = element.addElement(name);
el.addText(value);

}
public static void main(String[] args) throws Exception {

Document document = DocumentHelper.createDocument();
Element root = document.addElement("stakeapply"); //默认根节点
Element el = jsonToXml(STR_JSON, root);
System.out.println(el.asXML());
try {
//生成xml文件
String fileName = "test.xml";
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); // 指定XML编码
format.setExpandEmptyElements(true);//自动添加闭合标签
document.setXMLEncoding("UTF-8");
//指定文件路径,名字,格式
XMLWriter writer = new XMLWriter(
new FileOutputStream(new File("D:" + File.separator + fileName)), format);
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
json串
{
"stakeapply": {
"voltageLevel": "AC00062",
"stakeList": {
"stake": [
{
"stakeAssetNO": 45754745,
"otherStakeTypeRemark": "xxx",
"stationId": "547547547547"
},
{
"stakeAssetNO": 34325325322,
"otherStakeTypeRemark": "xxx",
"stationId": "52354645462"
}
]
},
"otherStationTypeRemark": "xxx",
"stationAddr": "哈哈",
"custLists": {
"custList": {
"custId": "7547547547",
"custPhone": 13666666666,
"contactMode": 1
}
},
"principalList": {
"principal": [
{
"principalName": 121212,
"principalType": 1
},
{
"principalName": 12121233,
"principalType": 1
}
]
}
}
}
*/

/*
转换后的xml
<?xml version="1.0" encoding="UTF-8"?>

<stakeapply>
<voltageLevel>AC00062</voltageLevel>
<stakeList>
<stake>
<stakeAssetNO>45754745</stakeAssetNO>
<otherStakeTypeRemark>xxx</otherStakeTypeRemark>
<stationId>547547547547</stationId>
</stake>
<stake>
<stakeAssetNO>34325325322</stakeAssetNO>
<otherStakeTypeRemark>xxx</otherStakeTypeRemark>
<stationId>52354645462</stationId>
</stake>
</stakeList>
<otherStationTypeRemark>xxx</otherStationTypeRemark>
<stationAddr>哈哈</stationAddr>
<custLists>
<custList>
<custId>7547547547</custId>
<custPhone>13666666666</custPhone>
<contactMode>1</contactMode>
</custList>
</custLists>
<principalList>
<principal>
<principalName>121212</principalName>
<principalType>1</principalType>
</principal>
<principal>
<principalName>12121233</principalName>
<principalType>1</principalType>
</principal>
</principalList>
</stakeapply>
*/
}