/** * 序列化为XML文件 */ public static <V> void toXmlFile(String path, V v, boolean isIndent) { try (Writer writer = new FileWriter(new File(path), true)) { if (isIndent) { xmlMapper.writerWithDefaultPrettyPrinter().writeValue(writer, v); } else { xmlMapper.writeValue(writer, v); } writer.flush(); } catch (Exception e) { log.error("jackson to xml file error, path: {}, obj: {}, isIndent: {}", path, v, isIndent, e); } }
/** * 序列化为XML */ public static <V> String toXml(V v, boolean isIndent) { try { if (isIndent) { return xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(v); } else { return xmlMapper.writeValueAsString(v); } } catch (JsonProcessingException e) { log.error("jackson to xml error, obj: {}, isIndent, {}", v, isIndent, e); return null; } }
/** * Attempts to pretty print the payload of an * HTTP request based on the headers. Only JSON * and XML are supported at the moment. * * @param payload Payload to be serialized in the request * @param headers Headers, should contain "Content-Type" * @return Pretty printed payload * @throws IOException If something went wrong when serializing the object */ public static String prettyPrintRequestPayload(Object payload, Map<String, String> headers) throws IOException { if (isContentTypeApplicationJson(headers)) { return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(payload); } else if (isContentTypeApplicationXml(headers)) { return xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(payload); } else { return "Payload not printable in the format specified by the Content-Type header."; } }
xmlMapper.setAnnotationIntrospector(new XmlAnnotationIntrospector()); ObjectMapper jsonMapper = new ObjectMapper(); System.out.println(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user)); System.out.println(jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));