xml转json
实现指定节点强制转数组, 从而实现xml单标签转数组
核心工具包
//因对接海关报文存在单标签转数组的情况,目前优先采用当前工具
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220320</version>
</dependency>
public static void main(String[] args){
String xml="<Package\n" +
" xmlns=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <EnvelopInfo>\n" +
" <receiver_id>4123123</receiver_id>\n" +
" <send_time>2022-09-06 12:08:00</send_time>\n" +
" </EnvelopInfo>\n" +
" <DataInfo>\n" +
" <PocketInfo>\n" +
" <pocket_id>QD512310709</pocket_id>\n" +
" <is_unstructured />\n" +
" </PocketInfo>\n" +
" <BussinessData>\n" +
" <CheckInfo>\n" +
" <note>报文入库成功</note>\n" +
" </CheckInfo>\n" +
" <CheckInfos>\n" +
" <note>报文入库成功</note>\n" +
" </CheckInfos>\n" +
" </BussinessData>\n" +
" </DataInfo>\n" +
"</Package>";
// 1.使用额外参数方式,补偿xml报文无法确认对象、数组缺陷
// 2.同步转换json对象时强制转换当前标签为数组
// 3.缺陷 只能设置标签,当不同层级存在同标签名但不同类型时会默认都转数组(不区分对象,数组)
// 4.优点 标签属性和xml命令空间可以很好的转换保留
Set<String> arrayNodes =new HashSet<String>();
arrayNodes.add("CheckInfo");
JSONObject json = new JSONObject(xmlToMap(xml, arrayNodes));
System.out.println(json);
}
public static Map<String, Object> xmlToMap(String xml, Set<String> arrayNodes) {
XMLParserConfiguration config = XMLParserConfiguration.KEEP_STRINGS;
// 设置withForceList配置强制数组标签名
if (CollectionUtils.isNotEmpty(arrayNodes)) config = config.withForceList(arrayNodes);
// 转json
// JSONObject json = XML.toJSONObject(xml, config);
// 转map
return XML.toJSONObject(xml, config)
}
转换后参数如下,优点可以保留当前报文的命令空间和标签属性
{
"Package": {
"DataInfo": {
"PocketInfo": {
"is_unstructured": "",
"pocket_id": "QD512310709"
},
"BussinessData": {
"CheckInfo": [
{
"note": "报文入库成功"
}
],
"CheckInfos": {
"note": "报文入库成功"
}
}
},
"xmlns": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"EnvelopInfo": {
"receiver_id": "4123123",
"send_time": "2022-09-06 12:08:00"
}
}
}
目前所使用版本20220320 挺优秀的工具可以学习关注下