jsonXML格式化核心代码
json格式化:
依赖:
<dependency><groupId>com.jayway.jsonpath</groupId><artifactId>json-path</artifactId><version>2.6.0</version><scope>compile</scope> </dependency>
string text = "{\"data\":{\"result\":true},\"path\":null,\"msgCode\":200,\"message\":\"请求成功\"}"; String s = JsonFormatter.prettyPrint(text);
xml格式化:
依赖:import org.xml.sax.InputSource;
调用: String xml = xmlFormat(text, 4, false);
/*** @Description 格式化xml* @param xmlString xml内容* @param indent 向前缩进多少空格* @param ignoreDeclaration 是否忽略描述* @return 格式化后的xml*/ public static String xmlFormat(String xmlString, int indent, boolean ignoreDeclaration) throws Exception{try {InputSource src = new InputSource(new StringReader(xmlString));Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);TransformerFactory transformerFactory = TransformerFactory.newInstance();transformerFactory.setAttribute("indent-number", indent);Transformer transformer = transformerFactory.newTransformer();transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");transformer.setOutputProperty(OutputKeys.INDENT, "yes");Writer out = new StringWriter();transformer.transform(new DOMSource(document), new StreamResult(out));return out.toString();} catch (Exception e) {throw new Exception(e);} }