使用XMLSerializer XML转json发现一个问题,需要后台处理!!!请教大神

qq_31484927 2018-03-15 10:31:30
<specialty nameCN="电测">
<step>
<signer staffID="800706" nameCN=""><![CDATA[]]></signer>
</step>
<step>
<signer staffID="090477" nameCN=""><![CDATA[]]></signer>
</step>
</specialty>
<specialty nameCN="节能">
<step>
<signer staffID="800608" nameCN=""><![CDATA[]]></signer>
<signer staffID="800808" nameCN=""><![CDATA[]]></signer>
</step>
<step>
<signer staffID="800602" nameCN=""><![CDATA[]]></signer>
<signer staffID="800803" nameCN=""><![CDATA[]]></signer>
</step>
</specialty>

通过xmlSerializer.read(xml).toString();
转换结果:

{
"@nameCN": "电测",
"step": [
{
"signer": {
"@staffID": "800706",
"@nameCN": "",
"#cdata-section":
}
},
{
"signer": {
"@staffID": "090477",
"@nameCN": "",
"#cdata-section":
}

}
]
},
{
"@nameCN": "节能",
"step": [
{
"signer": [
{
"@staffID": "800608",
"@nameCN": "",
"#cdata-section":
},
{
"@staffID": "800808",
"@nameCN": "",
"#cdata-section":
}
]
},
{
"signer": [
{
"@staffID": "800602",
"@nameCN": "",
"#cdata-section":
},
{
"@staffID": "800803",
"@nameCN": "",
"#cdata-section":
}
]
}
]
}
...全文
3894 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
zhgsaber 2020-12-04
  • 打赏
  • 举报
回复
推测是XML未格式化导致的。自己测试过,如果是自己模拟提交标准xml格式,用流读进来就没事,就不会出现数组误转对象问题。如果别人提交是一行字符串就会转换异常。拿你的xml字符串过下这个方法就好了 public static String formatXML(String xml) { String requestXML = null; try { // 拿取解析器 SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(xml)); if (null != document) { StringWriter stringWriter = new StringWriter(); // 格式化,每一级前的空格 OutputFormat format = new OutputFormat(" ", true); // xml声明与内容是否添加空行 format.setNewLineAfterDeclaration(false); // 是否设置xml声明头部 format.setSuppressDeclaration(false); // 是否分行 format.setNewlines(true); XMLWriter writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); writer.close(); requestXML = stringWriter.getBuffer().toString(); } return requestXML; } catch (Exception e) { e.printStackTrace(); return null; } }
COOL_3 2018-07-30
  • 打赏
  • 举报
回复
博主,有转换的代码提供吗,我xml转json的时候 cdata部分直接显示里面内容 而没有cdata标识。
qq_31484927 2018-03-15
  • 打赏
  • 举报
回复
上面的结果 用红色标记出来的就是差别,step下有多个signer节点时,输出结果signer是数组, 只有1个signer节点 输出signer不是数组,如何在只有一个signer节点时也输出为数组
qq_31484927 2018-03-15
  • 打赏
  • 举报
回复
引用 2 楼 u011594442 的回复:
改元码?想不到别的啥办法ε=(´ο`*)))~
之前也有人遇到这种问题,只有一个附上了方法: 有一个方案,但不在好,也就是把xml先反序列化,反序列化时要写类来反序列化,然后再序列化成json。 在页面用一个插件检验节点是否为数组,不是则转为数组; 但是我这个是别人后台请求我的接口
Sunyiban 2018-03-15
  • 打赏
  • 举报
回复
改元码?想不到别的啥办法ε=(´ο`*)))~

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧