package org.luck.xml;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.junit.jupiter.api.Test;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import java.io.File;
public class JsonToXml {
private static final String json ="{\"configuration\":{\"pa\":{\"-name\":\"party\",\"papa\":{\"-active\":\"pm 11:10:10\",\"#text\":\"Party hotel\"}},\"wumans\":{\"wuman\":[{\"-name\":\"tic\",\"#text\":\"1\"},{\"-name\":\"sa\",\"#text\":\"2\"},{\"-name\":\"mis zhang\",\"#text\":\"3\"},{\"-name\":\"mis li\",\"#text\":\"4\"}]},\"active\":[\"underground\",\"public\"],\"mans\":{\"man\":[{\"-name\":\"tom\",\"#text\":\"1\"},{\"-name\":\"jact\",\"#text\":\"2\"},{\"-name\":\"pa\",\"#text\":\"3\"},{\"-name\":\"mr li\",\"#text\":\"4\"}]}}}";
@Test
public void test() throws ParserConfigurationException, TransformerException {
//获取json的解析器 并解析json字符串
JsonElement je = new JsonParser().parse(json);
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.setXmlVersion("1.0");
System.out.println(document.toString());
parse(je, document,document,null);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document),new StreamResult(new File("C:\\Users\\Administrator\\Desktop\\notebook\\test1.xml")));
}
/**
* 解析json
*/
private void parse(JsonElement je, Document document, Node element,String name){
if(je.isJsonObject()){
JsonObject jo = je.getAsJsonObject();
//获取节点的所有子节点
jo.entrySet().forEach(x->{
String key = x.getKey();
Node parse;
if(key.equals("#text")){
parse = document.createTextNode(key);
parse(x.getValue(),document,parse,null);
element.appendChild(parse);
}else if(key.startsWith("-")) {
String keyWord = key.substring(1);
Attr attribute = document.createAttribute(keyWord);
attribute.setValue(((JsonPrimitive)x.getValue()).getAsString());
((Element)element).setAttributeNode(attribute);
}else {
if(x.getValue().isJsonArray()){
parse(x.getValue(),document,element,key);
}else{
parse = document.createElement(key);
parse(x.getValue(),document,parse,key);
element.appendChild(parse);
}
}
});
}else if(je.isJsonArray()){//数组节点
je.getAsJsonArray().forEach(x->{
Element parse = document.createElement(name);
parse(x, document,parse,name);
element.appendChild(parse);
});
}else if(je.isJsonPrimitive()){
element.setTextContent(je.getAsJsonPrimitive().getAsString());
}
}
}