用java json 转 xml 加头
时间: 2023-09-20 11:06:20 浏览: 72
json 转 xml
你可以使用Java中的Jackson库来将JSON转换为XML,并且使用Java中的DOM API来添加XML头。以下是一个示例代码:
```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
public class JsonToXmlConverter {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Convert JSON to XML
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
appendJsonNodeToXmlElement(jsonNode, root, doc);
// Add XML header
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(sw));
String xml = sw.toString();
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + xml;
System.out.println(xml);
}
private static void appendJsonNodeToXmlElement(JsonNode jsonNode, Element element, Document doc) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
objectNode.fields().forEachRemaining(entry -> {
String key = entry.getKey();
JsonNode value = entry.getValue();
Element childElement = doc.createElement(key);
element.appendChild(childElement);
appendJsonNodeToXmlElement(value, childElement, doc);
});
} else if (jsonNode.isArray()) {
jsonNode.elements().forEachRemaining(childNode -> appendJsonNodeToXmlElement(childNode, element, doc));
} else if (jsonNode.isValueNode()) {
String value = jsonNode.asText();
element.appendChild(doc.createTextNode(value));
}
}
}
```
这将输出以下XML:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<name>John</name>
<age>30</age>
<city>New York</city>
</root>
```
阅读全文