java xml 轉json


public void xmlToJSON(Element element, JSONObject json) throws JSONException {        
        var elementAttributes = element.attributes();
        var elementText = element.getText();
        List<Element> childElements = element.elements();

        for (Object Attribute : elementAttributes) {
            Attribute attr = (Attribute) Attribute;
            if (!isEmpty(attr.getValue())) {
                json.put("@" + attr.getName(), attr.getValue());
            }
        }

        if (!isEmpty(elementText)) {
            json.put("#text", element.getText());
        }
        for (Element childElement : childElements) {
            JSONObject childJSON = new JSONObject();
            xmlToJSON(childElement, childJSON);
            Object childObject = json.get(childElement.getName());
            if (childObject != null) {
                JSONArray jsona = null;
                if (childObject instanceof JSONObject) {//如果此元素已存在,則轉為jsonArray
                    JSONObject jsono = (JSONObject) childObject;
                    json.remove(childElement.getName());
                    jsona = new JSONArray();
                    jsona.add(jsono);
                    jsona.add(childJSON);
                }
                if (childObject instanceof JSONArray) {
                    jsona = (JSONArray) childObject;
                    jsona.add(childJSON);
                }
                json.put(childElement.getName(), jsona);
            } else {
                if (!childJSON.isEmpty()) {
                    json.put(childElement.getName(), childJSON);
                }
            }
        }

    }

 啥也不想說了. 上一個版本叫我覆蓋掉了.  . .

湊合看吧

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM