1.更简单的方法:
使用第三方库,
1.加入依赖
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
2.
public static void main(String[] args) {
String xmlString = "//";
// XML转换为JSON
JSONObject jsonObject = XML.toJSONObject(xmlString);
log.info("json:{}",jsonObject);
}
---------------------------------------------------------------------------------------------------------------------
2.自己封装工具类
步骤
1.CV,CV~
2.格式化你的输入的xml数据。(如下图)
需要格式化的xml数据
输出结果:
格式化后的数据:
详细代码:
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);
}
}
}
}
}