他山之石
Maven依赖
1 <!--Jackson 2.x ,有三个jar,jackson-core-2.x.x.jar(核心jar包), 2 jackson-annotations-2.x.x.jar(该包提供Json注解支持) 3 jackson-databind-2.x.x.jar 4 annotations依赖core,databind依赖annotations,所以pom中只需要加databind的依赖即可 5 --> 6 7 <dependency> 8 <groupId>com.fasterxml.jackson.core</groupId> 9 <artifactId>jackson-databind</artifactId> 10 <version>2.9.3</version> 11 </dependency>
实践代码
1 import cn.mamp.Json.User; 2 import com.fasterxml.jackson.core.JsonProcessingException; 3 import com.fasterxml.jackson.databind.ObjectMapper; 4 import org.junit.Test; 5 6 import java.io.IOException; 7 8 public class JacksonUse { 9 @Test 10 public void objectMapperUser() { 11 ObjectMapper objectMapper = new ObjectMapper(); 12 User user = new User(); 13 user.setAge(123); 14 try { 15 // Obj -> String 16 String userJsonStr = objectMapper.writeValueAsString(user); 17 System.out.println(userJsonStr); // 默认序列化null值:{"name":null,"age":123} 18 19 // String -> obj 20 User u = objectMapper.readValue(userJsonStr, User.class); 21 System.out.println(u); 22 23 } catch (JsonProcessingException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 }