XML转JSON格式

326 阅读1分钟

1.更简单的方法:

使用第三方库,

1.加入依赖

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20230227</version>
</dependency>

image.png

public static void main(String[] args) {
    String xmlString = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<xxx:xxx xxx:xxx="https://blog.csdn.net/blizzardSniper" xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" ns3:schemaLocation="https://blog.csdn.net/blizzardSniper /xxxx.xsd">\n    <name>华为mate60 pro</name>\n        <stocksList>\n        <normalStockList>\n                       <type>product</type>\n            <num>50</num>\n            <cost>9500.00</cost>\n        </normalStockList>\n    </stocksList>\n</xxx:xxx>\n";
    // XML转换为JSON
    JSONObject jsonObject = XML.toJSONObject(xmlString);
    log.info("json:{}",jsonObject);

}

2.封装一个工具类进行转换。(代码在最下方)

步骤

1.CV,CV~

2.格式化你的输入的xml数据。(如下图)

需要格式化的xml数据

image.png

输出结果: image.png

格式化后的数据: image.png

详细代码:

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

@Slf4j
public class XMLToJsonConverter {

    public static void main(String[] args) throws Exception {
        String xmlString = "//please init your xml data by String";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlString)));

        Element rootElement = document.getDocumentElement();
        JSONObject json = convertElementToJson(rootElement);
        log.info("json:{}",json);

    }

    private static JSONObject convertElementToJson(Element element) {
        JSONObject json = new JSONObject();
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) node;
                convertElementToJson(childElement, json);
            }
        }
        return json;
    }

    private static void convertElementToJson(Element element, JSONObject parentJson) {
        NodeList nodeList = element.getChildNodes();
        if (nodeList.getLength() == 1 && nodeList.item(0).getNodeType() == Node.TEXT_NODE) {
            parentJson.put(element.getNodeName(), element.getTextContent());
        } else {
            JSONArray currentArray = null;
            if (parentJson.containsKey(element.getNodeName())) {
                Object existingValue = parentJson.get(element.getNodeName());
                if (existingValue instanceof JSONArray) {
                    currentArray = (JSONArray) existingValue;
                } else {
                    currentArray = new JSONArray();
                    currentArray.add(existingValue);
                    parentJson.put(element.getNodeName(), currentArray);
                }
            } else {
                currentArray = new JSONArray();
                parentJson.put(element.getNodeName(), currentArray);
            }
            JSONObject currentObject = new JSONObject();
            currentArray.add(currentObject);
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element childElement = (Element) node;
                    convertElementToJson(childElement, currentObject);
                }
            }
        }
    }
}