需求
- 第三方传回的报文格式是xml,需要转成json进行传输
方案
- 在尝试过xstream,org.json等包后,最后选择了json-lib
- json-lib的转换会默认把头结点去掉,对我目前的项目来讲反而有利,配合fastjson转对象也很方便
步骤
- 引入pom
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.2</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>
- 封装方法
public static String toJSONString(String xml){
XMLSerializer xmlSerializer = new XMLSerializer();
String resutStr = xmlSerializer.read(xml).toString(0);//0表示去除换行空格等,1以上表示json格式化后的数据
return resutStr;
}
- 结果
<ap>
<plain>
<mchnt_cd>0006410F0026868</mchnt_cd>
<mchnt_txn_ssn>900123456789</mchnt_txn_ssn>
<resp_code>0000</resp_code>
<resp_desc>成功</resp_desc>
<login_id>15869696969</login_id>
</plain>
<signature>auK8wfMTw</signature>
</ap>
11:03:43.935 [main] INFO net.sf.json.xml.XMLSerializer - Using default type string
{
"plain": {
"mchnt_cd": "0006410F0026868",
"mchnt_txn_ssn": "900123456789",
"resp_code": "0000",
"resp_desc": "成功",
"login_id": "15869696969"
},
"signature": "auK8wfMTw"
}