Hutool XML 转JSON 后 parseArray踩坑

XML转JSON

    public static String getSingleAcString() {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<list>\n" +
                "<acBasicInfo>\n" +
                "    <label>JingChang-AC-A</label>\n" +
                "    <sysName>JingChang-AC-A</sysName>\n" +
                "    <status>0</status>\n" +
                "    <ipAddress>10.153.129.64</ipAddress>\n" +
                "    <type>H3C WX6100EWPX</type>\n" +
                "    <pingStatus>1</pingStatus>\n" +
                "    <macAddress>00:23:89:16:51:80</macAddress>\n" +
                "    <softwareVersion>Release 2109P05</softwareVersion>\n" +
                "    <hardwareVersion></hardwareVersion>\n" +
                "    <serialId></serialId>\n" +
                "    <onlineApCount>16</onlineApCount>\n" +
                "    <onlineClientCount>19</onlineClientCount>\n" +
                "</acBasicInfo>\n" +
                "</list>";
        return xml;
    }
 String string = XmlExample.getSingleAcString();
        JSONObject json = JSONUtil.parseFromXml(string);
        JSONObject list = (JSONObject) json.get("list");
        JSONArray jsonArray = JSONUtil.parseArray(list.get("acBasicInfo"));
        List<AcPerfInfo> acPerfInfos = JSONUtil.toList(jsonArray, AcPerfInfo.class);
        acPerfInfos.stream().forEach(System.out::println);

想将acBasicInfo转成list集合
在这里插入图片描述
理想状态是 list里面有一个 AcPerfInfo对象 实际上变成了12 的对象 里面有12 个属性
在这里插入图片描述
在这里插入图片描述
解决方案
判断标签出现次数 出现次数大于 1 就 用toList方法 小于 就转为对象 再加入集合

    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        int index = 0;
        while ((index = srcText.indexOf(findText, index)) != -1) {
            index = index + findText.length();
            count++;
            if (count >= 2){
                return count;
            }
        }
        return count;
    }
 JSONObject json = JSONUtil.parseFromXml(acResult);
        JSONObject list = (JSONObject) json.get("list");
        List<AcBasicInfoResVo> acList = new ArrayList<>();
        int amount = appearNumber(acResult, "</acBasicInfo>");
        //amount 为 1 时 有坑 单独处理
        if (amount == 1) {
            JSONObject single = (JSONObject) list.get("acBasicInfo");
            AcBasicInfoResVo acBasicInfoResVo = single.toBean(AcBasicInfoResVo.class);
            acList.add(acBasicInfoResVo);
        } else {
            JSONArray jsonArray = JSONUtil.parseArray(list.get("acBasicInfo"));
            acList = JSONUtil.toList(jsonArray, AcBasicInfoResVo.class);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值