java json 轉為xml檔案
阿新 • • 發佈:2018-11-23
1.jar包引用
<dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/xom/xom --> <dependency> <groupId>xom</groupId> <artifactId>xom</artifactId> <version>1.0</version> </dependency>
2.main方法
package com.han; import org.apache.commons.io.FileUtils; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import net.sf.json.JSONObject; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; public class XmlFormatter { //格式化 public String format(String unformattedXml) { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new RuntimeException(e); } } private Document parseXmlFile(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } //轉化為String public static String jsonToXML(String json) { net.sf.json.xml.XMLSerializer xmlSerializer = new net.sf.json.xml.XMLSerializer(); // 根節點名稱 xmlSerializer.setRootName("resource"); // 不對型別進行設定 xmlSerializer.setTypeHintsEnabled(false); String xmlStr = ""; JSONObject jobj = JSONObject.fromObject(json); xmlStr = xmlSerializer.write(jobj); return xmlStr; } public static void main(String[] args) throws Exception{ String aa = "{\"index\":\"0\",\"title\":null,\"order\":\"0\",\"componentKey\":\"ColumnPanel\",\"layoutDetail\":[{\"aa\":\"12\"}]}"; // String original_filename= "/Users/xidehan/Downloads/aa.txt"; //String file = FileUtils.readFileToString(new File(original_filename)); String s = jsonToXML(file); System.out.println(new XmlFormatter().format(s)); PrintWriter writer = new PrintWriter("/Users/xidehan/Downloads/resource.xml", "UTF-8"); writer.println(new XmlFormatter().format(s)); writer.close(); }