最近做中间接口对接和格式转换,我需要在中间实现json和xml互转,但是出现了一个问题,当json串中包含数组时,会把同一个节点的多个内容放在一个节点里,导致转换为xml的时候只要一个父节点,如图所示:

我们目前需要的格式应该是多个节点包含,效果如下:

再来个变态点的json,转完效果如下:

接下来上代码,是用递归实现的,大家参考参考

引入依赖

<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
        <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.0.0</version>
        </dependency>

实现代码

@SpringBootTest
class Json2xmlApplicationTests {

    @Test
    void contextLoads() {
		String jsonArr2 ="{\"TxnBatchNo\": \"20170607152322\",\"TxnSeq\": \"1\",\"CardNo\": \"2017000100000003\",\"AAA\": {\"hello\": \"nihao\",\"hey\": \"hai\",\"world\": \"hee\"},\"BBB\": [{\"hello\": \"nihao\",\"hey\": \"hai\",\"people\": [{\"d\": \"dog\",\"c\": \"\",\"e\": [{\"hello\": \"nihao\",\"hey\": \"hai\",\"tiger\": [{\"d\": \"dog\",\"c\": \"\",\"e\": \"elepahant\"}]}]}]}]}";
        String personStr = "{ \"programmers\": [ { \"firstName\": \"Brett\", \"lastName\":\"McLaughlin\", \"email\": \"aaaa\" },{ \"firstName\": \"Jason\", \"lastName\":\"Hunter\", \"email\": \"bbbb\" },{ \"firstName\": \"Elliotte\", \"lastName\":\"Harold\", \"email\": \"cccc\" }]}";
        String json2XmlString = json2XmlString(jsonArr2,"people");
		System.out.println(json2XmlString);
    }

    //处理json数组转xml丢节点问题
    public static String json2XmlString(String jsonStr,String rootName){
        JSONObject jsonObj = null;
        String xmlResult = "";
        if(StringUtils.isNotBlank(jsonStr)){
            try {
                jsonObj = JSONObject.fromObject(jsonStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 创建dom对象
            Document document = DocumentHelper.createDocument();
            // 设置编码格式
            document.setXMLEncoding("utf-8");
            Element parentElement = document.addElement(rootName);
            Set<String> keySet = jsonObj.keySet();
            for (String key : keySet) {
                // 判断此时key的value是否是json数组
                Object json = jsonObj.get(key);
                if (json instanceof JSONArray) {
                    // 处理json数组
                    jsonArrayToXml((JSONArray) json, parentElement,key);
                } else if (json instanceof JSONObject) {
                    Element childrenElement = parentElement.addElement(key);
                    JSONObject object = (JSONObject) jsonObj.get(key);
                    for (Object key2 : object.keySet()) {
                        Element childrenElement2 = childrenElement.addElement(String.valueOf(key2));
                        // 再次判断
                        if (jsonObj.get(key2) instanceof JSONArray) {
                            jsonArrayToXml((JSONArray) jsonObj.get(key2), childrenElement2,String.valueOf(key2));
                        } else {
                            childrenElement2.setText(object.getString(String.valueOf(key2)));
                        }
                    }
                } else {
                    Element childrenElement = parentElement.addElement(key);
                    childrenElement.setText(jsonObj.get(key).toString());
                }

            }
            xmlResult = document.asXML();//如果不要第一行,可以这样写document.getRootElement().asXML();
        }else{
            xmlResult = "<"+rootName+"></"+rootName+">";
        }

        return xmlResult;
    }
    /**
     *
     * @param jsonArray
     * @param parentElement
     * @param parentKey 父节点
     */
    public static void jsonArrayToXml(JSONArray jsonArray, Element parentElement, String parentKey) {
        for (int i = 0; i < jsonArray.size(); i++) {
            Element childrenElement = parentElement.addElement(parentKey);
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            for (Object key : jsonObject.keySet()) {

                Object arry = jsonObject.get(key);
                if (arry instanceof JSONArray) {
                    // 递归
                    jsonArrayToXml((JSONArray) arry, childrenElement,key+"");
                } else {
                    Element addElement = childrenElement.addElement(String.valueOf(key));
                    addElement.setText(jsonObject.get(key).toString());
                }
            }
        }
    }

}

有问题留言,我会及时回复,共勉!

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐