1.美化POJO序列化xml 下面將POJO列化為xml并打印。 Person person = new Person(); //設(shè)置person屬性 ObjectMapper mapper = new XmlMapper(); System.out.println(mapper.writeValueAsString(person)); 但是輸出為緊湊模式: 2.目的:美化過的輸出 有時(shí)希望能夠美化輸出,更方便閱讀和理解,如: 方式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時(shí),操作基本一致,只需要使用ObjectMapper替代XmlMapper。如: Person person = new Person(); //設(shè)置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
1.美化POJO序列化xml下面將POJO列化為xml并打印。Person person = new Person();//設(shè)置person屬性O(shè)bjectMapper mapper = new XmlMapper();System.out.println(mapper.writeValueAsString(person));但是輸出為緊湊模式:
2.目的:美化過的輸出有時(shí)希望能夠美化輸出,更方便閱讀和理解,如:方式1.使用:writerWithDefaultPrettyPrinterObjectMapper mapper = new XmlMapper();System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person));mapper.enable(SerializationFeature.INDENT_OUTPUT);方式2.使用:SerializationFeature.INDENT_OUTPUTObjectMapper mapper = new XmlMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.writeValueAsString(person);
3.序列化為json序列化為json時(shí),操作基本一致,只需要使用ObjectMapper替代XmlMapper。如:Person person = new Person();//設(shè)置person屬性O(shè)bjectMapper mapper = new ObjectMapper();System.out.println(mapper.writeValueAsString(person));激活美化的方式,同樣可以是2.1和2.2介紹的方式。
4.包依賴序列化為xml依賴:jackson-databindjackson-corejackson-dataformat-xml序列化為json依賴:jackson-databindjackson-core