如何使用jackson美化輸出json/xml


如何使用jackson美化輸出json/xml

1.美化POJO序列化xml

下面將POJO列化為xml並打印。

Person person = new Person();
//設置person屬性

ObjectMapper mapper = new XmlMapper();
System.out.println(mapper.writeValueAsString(person));

但是輸出為緊湊模式:

<Person><name>Hello world</name><age>12</age></Person>

2.目的:美化過的輸出

有時希望能夠美化輸出,更方便閱讀和理解,如:

<Person>
  <name>Hello world</name>
  <age>12</age>
</Person>

方式1.使用:writerWithDefaultPrettyPrinter

ObjectMapper mapper = new XmlMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person));
 mapper.enable(SerializationFeature.INDENT_OUTPUT);

方式2.使用:SerializationFeature.INDENT_OUTPUT

ObjectMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(person);

3.序列化為json

序列化為json時,操作基本一致,只需要使用ObjectMapper替代XmlMapper。如:

Person person = new Person();
//設置person屬性

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(person));

激活美化的方式,同樣可以是2.1和2.2介紹的方式。

4.包依賴

序列化為xml依賴:

  • jackson-databind
  • jackson-core
  • jackson-dataformat-xml

序列化為json依賴:

  • jackson-databind
  • jackson-core
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.2</version>
</dependency>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM