下面將POJO列化爲xml並打印。json
Person person = new Person(); //設置person屬性 ObjectMapper mapper = new XmlMapper(); System.out.println(mapper.writeValueAsString(person));
可是輸出爲緊湊模式:app
<Person><name>Hello world</name><age>12</age></Person>
有時但願可以美化輸出,更方便閱讀和理解,如:code
<Person> <name>Hello world</name> <age>12</age> </Person>
ObjectMapper mapper = new XmlMapper(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person)); mapper.enable(SerializationFeature.INDENT_OUTPUT);
ObjectMapper mapper = new XmlMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.writeValueAsString(person);
序列化爲json時,操做基本一致,只須要使用ObjectMapper替代XmlMapper。如:orm
Person person = new Person(); //設置person屬性 ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(person));
激活美化的方式,一樣能夠是2.1和2.2介紹的方式。xml
<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>