以下是 Java 8 原生 JSON 转 XML 的示例代码:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import java.io.IOException;

public class JsonToXml {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        // JSON字符串
        String jsonString = '{"person":{"name":"John","age":30,"address":{"street":"123 Main St","city":"New York"}}}';

        // 将JSON字符串转换为JSONObject对象
        JSONObject jsonObject = new JSONObject(jsonString);

        // 将JSONObject对象转换为XML字符串
        String xmlString = XML.toString(jsonObject);

        // 将XML字符串转换为Document对象
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(xmlString);

        // 输出Document对象
        System.out.println(document);
    }
}

运行上述代码,将输出以下内容:

[#document: null]

如果要将 Document 对象转换为 XML 字符串,则可以使用以下代码:

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

// ...

// 将Document对象转换为XML字符串
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(System.out);
transformer.transform(domSource, streamResult);

这样就可以将 Document 对象输出为 XML 字符串。

Java 8 原生 JSON 转 XML 示例 - 使用 JSONObject 和 XML 库

原文地址: https://www.cveoy.top/t/topic/nytC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录