将Map(含多层嵌套)转为XML格式
将数据转为xml格式,我们常⽤的是采⽤Dom4j对数据进⾏解析,但对⼀些特殊格式的数据解析时,其就不⽀持,说数据有问题
例如以下json格式字符串数据
{
"result": [{
"1": {
"total": "5",
"code": "300040",
"accrate": "0.02",
"change": "54",
"name": "九洲电⽓",
"totalcap": "39.69",
"time": "20180331",
"changesta": "-0.24",
"fundnum": {
"num": "12",
"size": {
"id":"1001",
"adress":"北京市"
}
}
},
"2": {
"total": "6",
"code": "300041",
"accrate": "0.12",
"change": "154",
"name": "中国邮电",
"totalcap": "39.69",
"time": "20180431",
"changesta": "-0.24",
"fundnum": {
"num": "169",
"size": {
"id":"1002",
"adress":"深圳市"
}
}
}
}],
"reason": "SUCCESSED!",
"error_code": 0,
"resultcode": "200"
}
错误(不⽀持)的原因是:是因为该json格式中存在以数字为key,说其不是正规格式数据,但客户接⼝其响应结果就是这种格式数据,⽽我们需要转为xml格式呈现,咋办呢?
我的做法是⾸先将该json格式字符串转成map,然后将map转xml (注:不采⽤dom4j,理由已经说明了,不信可以将以上数据转⼀下试试)第⼀步:json字符串转 Map
Map<String,Object> map = JSON.parseObject(str);
第⼆步:对Map进⾏递归解析拼接
/**
* @Description:TODO(循环遍历map节点和value,拼接成xml)
使用dom4j解析xml文件* @param: Map<?, ?> map
* @param: StringBuffer
* @return:
* @auther: xushaowen
* @date: 2019/8/19 11:04
* @throws
*
**/
public static void mapToXML(Map<?, ?> map, StringBuffer sb) { Set<?> set = map.keySet();
for (Iterator<?> it = set.iterator(); it.hasNext();) {
String key = (String) it.next();
Object value = (key);
if (value instanceof Map) {
sb.append("<" + key + ">\n");
mapToXML((Map<?, ?>) value, sb);
sb.append("</" + key + ">\n");
} else if (value instanceof List) {
List<?> list = (List<?>) (key);
for (int i = 0; i < list.size(); i++) {
sb.append("<" + key + ">\n");
Map<?, ?> hm = (Map<?, ?>) (i);
mapToXML(hm, sb);
sb.append("</" + key + ">\n");
}
} else {
sb.append("<" + key + ">" + value + "</" + key + ">\n"); }
}
}
最后封装调⽤
public static String getXmlByMap(Map<?, ?> map) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); sb.append("<root>\n");
mapToXML(map, sb);
sb.append("</root>");
String();
}
结果展⽰
<?xml version="1.0" encoding="utf-8"?> <root>
<result>
<1>
<total>5</total>
<code>300040</code>
<accrate>0.02</accrate>
<change>54</change>
<name>九洲电⽓</name>
<totalcap>39.69</totalcap>
<time>20180331</time>
<changesta>-0.24</changesta> <fundnum>
<size>
<adress>北京市</adress>
<id>1001</id>
</size>
<num>12</num>
</fundnum>
</1>
<2>
<total>6</total>
<code>300041</code>
<accrate>0.12</accrate>
<change>154</change>
<name>中国邮电</name>
<totalcap>39.69</totalcap>
<time>20180431</time>
<changesta>-0.24</changesta> <fundnum>
<size>
<adress>深圳市</adress>
<id>1002</id>
</size>
<num>169</num>
</fundnum>
</2>
</result>
<reason>SUCCESSED!</reason>
<error_code>0</error_code>
<resultcode>200</resultcode>
</root>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论