本文主要是介绍Jackson实现JSON格式化输出,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在某些情况下我们希望JSON按照一个比较友好的格式换行输出,不要都挤在一起,可以使用JACKSON实现。
- 引入Jackson
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.5</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.5</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.5</version>
</dependency>
- 格式化输出测试
public class JacksonTest {@Testpublic void test1() throws IOException {ObjectMapper mapper = new ObjectMapper();List list = new ArrayList<>();Map map1 = new HashMap<>();map1.put("id","111");map1.put("users", Arrays.asList(1,2,3,4,5,5));list.add(map1);Map map2 = new HashMap();map2.put("name","zqw");list.add(map2);//普通输出System.out.println(mapper.writeValueAsString(list));//格式化/美化/优雅的输出System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list));String str = "[ {\n" +" \"id\" : \"111\",\n" +" \"users\" : [ 1, 2, 3, 4, 5, 5 ]\n" +"}, {\n" +" \"name\" : \"zqw\"\n" +"} ]";Object obj = mapper.readValue(str, Object.class);System.out.println(mapper.writeValueAsString(obj));System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));}
}
这篇关于Jackson实现JSON格式化输出的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!