JSONObject转换xml
时间: 2023-12-29 11:04:38 浏览: 68
json 转 xml
你可以使用以下步骤来将JSONObject转换为XML:
1. 创建一个新的Document对象。
2. 将JSONObject的数据逐个遍历,以键值对的形式添加到新的Document对象中。
3. 使用Transformer将Document对象转换为XML字符串。
下面是一个示例代码,使用Java中的org.json和org.w3c.dom库来实现JSONObject到XML的转换:
```java
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class JsonToXmlConverter {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject("{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("data");
document.appendChild(rootElement);
addJsonObjectToElement(jsonObject, document, rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addJsonObjectToElement(JSONObject jsonObject, Document document, Element element) {
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
Element subElement = document.createElement(key);
element.appendChild(subElement);
addJsonObjectToElement((JSONObject) value, document, subElement);
} else {
Element subElement = document.createElement(key);
subElement.appendChild(document.createTextNode(value.toString()));
element.appendChild(subElement);
}
}
}
}
```
运行上述代码,会将JSONObject `{"name":"John","age":30,"city":"New York"}` 转换为如下的XML字符串:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<name>John</name>
<age>30</age>
<city>New York</city>
</data>
```
阅读全文