添加jackson依賴:
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.2' // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.2' // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.8.2'
看到fasterxml還以為找錯依賴,還以為和com.alibaba:fastjson這個有啥聯系,還以為是一個叫做jack的人寫的。為啥有三個依賴,當發現大多數的框架都依賴於jackson來處理json轉換的時候就自然而然的當做理所當然了。
POJO序列化為json字符串:
准備一個POJO:
@JsonIgnoreProperties(ignoreUnknown = true) class User implements Serializable { private static final long serialVersionUID = -5952920972581467417L; private String name; public User() { } public User(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return "User{" + "name=" + name + '}'; } }
-
@JsonIgnoreProperties(ignoreUnknown = true) 是為了反序列化的時候,如果遇到不認識的filed,忽略之
- 無參構造函數是為了在反序列化的時候,jackson可以創建POJO實例
- getter方法是為了序列化的時候,jackson可以獲取filed值
- toString是方便我自己debug看顯示
- 至於Serializable,習慣的給實體增加一個持久化的能力。
通過write來轉化成jason字符串:
String expected = "{\"name\":\"Test\"}"; String test = mapper.writeValueAsString(new User("Test")); Assert.assertEquals(expected, test);
通過read來parse json字符串為POJO對象:
User user = mapper.readValue(expected, User.class); Assert.assertEquals("Test", user.getName());
jsonArray轉換成Array數組:
String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]"; ArrayType arrayType = mapper.getTypeFactory().constructArrayType(User.class); User[] users = mapper.readValue(expected, arrayType); Assert.assertEquals("Ryan", users[0].getName());
jsonArray轉換成List<>泛型:
expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class); //the sieze of the list is dependon the str json length although the json content is not the POJO type maybe List<User> userList = mapper.readValue(expected, listType); Assert.assertEquals(3, userList.size()); Assert.assertNull(userList.get(0).getName()); Assert.assertEquals("Ryan",userList.get(2).getName());
jackson默認將對象轉換為LinkedHashMap:
String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]"; ArrayList arrayList = mapper.readValue(expected, ArrayList.class); Object o = arrayList.get(0); Assert.assertTrue(o instanceof LinkedHashMap);