Jackson消息转换器

Jackson

json的概念

json是一种应用广泛的数据交换格式,例如:

{
    "name": "admin",
    "age": 20,
    "hobbies":["唱","跳","rap"]
}

Jackson就是将Java对象与Json数据进行相互转换的工具。

public class {
    private String name;
    private int age;
    private String[] hobbies
}

Jackson是Spring默认使用的Json转化器,有依赖少,稳定性高,API丰富等优点

使用方法:

引入依赖

<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-coreartifactId>
dependency>
 
<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-annotationsartifactId>
dependency>
 
<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-databindartifactId>
dependency>

<dependency>
  <groupId>com.fasterxml.jackson.datatypegroupId>
  <artifactId>jackson-datatype-jsr310artifactId>
  <version>2.10.1version>
dependency>

如果采用Spring boot框架开发,会自动引入Jackson的全部依赖

1. 序列化

Jackson需要使用ObjectMapper进行序列化,并且他是线程安全的,可以设定为成员变量

@SpringBootTest
class JacksonApplicationTests {
	private static final String DATE_TIME_FORMAT = "yyyy-MM--dd HH:mm:ss";
    
	//json转化器
    private static ObjectMapper objectMapper = new ObjectMapper();
	
	//全局配置序列化
	static {
		//设置为不包含null值
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //对于单个的bean进行配置可以在其实体类上添加@JsonInclude(JsonInclude.Include.NON_NULL)注解
	}
	/**
     * 序列化
     */
    @Test
    void serializeTest() throws JsonProcessingException {
        User user = new User();
        String[] hobbies = {"sing","dance","rap"};
        //Jackson默认包含null值
        //user.setId(1L);
        user.setUsername("kunkun");
        user.setAge(22);
        user.setHobbies(hobbies);
        user.setRegisterDate(new Date());
        user.setBirthday(LocalDateTime.now());
        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);
    }
}

2.对于日期格式化

//首先可以在实体类上添加注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date registerDate;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime birthday;

//修改全局配置
//自动通过spi发现jackson的module并注册
objcetMapper.findAndRegisterModules();
//手动配置JavaTimeModule
JavaTimeModule javaTimeModule = new JavaTimeModule( );
javaTimeModule.addSerializer(LocalDateTime.classnew LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
//注册
objectMapper.registerModule(javaTimeModule);

3. 反序列化

//前端传来的json字符串
String str = "Json字符串";
//需要传入json和指定的反序列化类型
User usedr = objectMapper.readValue(str, User.class);


//忽略不存在的key,当json中含有实体类中不存在的属性,忽略
//FastJson默认就选择忽略
//在静态代码块中配置属性,这两种写法都可以
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


//对泛型的处理
String str = "前端传来的带有泛型的json";

ResultDTO<User> userResultDTO = objectMapper.readValue(str, new TypeReference<ResultDTO<User>>()) {};

4. 通用配置

//通用配置统一在静态代码块中
//驼峰转下划线  userName <---> user_name
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);


//在实体类上标注@JsonIgnore  表示忽略该属性
@JsonIgnore
private String password;

5. 对象更新

//对象更新,如果后者有值,则使用后者,否则前者的值不变
@Test
void test() throws Exception {
    User originalUser = new User();
    originalUser.setId(1L);
    originalUser.setName("Angelday");
    originalUser.setAge(21);
    
    User newUser = new User();
    newUser.setId(2L);
    newUser.setAge(22);
    User updatedUser = objectMapper.updateValue(originalUser, newUser);
    
    //id: 2 name: Angelday age: 22
    System.out.println(updatedUser);
}

应用

我们自定义的Jackson配置信息可以写到配置文件中

# 设置日期格式  
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss  
  
# 设置时区  
spring.jackson.time-zone=Asia/Shanghai  
  
# 忽略无法识别的字段  
spring.jackson.deserialization.fail-on-unknown-properties=false  
  
# 忽略空值字段  
spring.jackson.default-property-inclusion=non_null
spring:  
  jackson:  
    date-format: yyyy-MM-dd HH:mm:ss  
    time-zone: Asia/Shanghai  
    deserialization:  
      fail-on-unknown-properties: false  
    default-property-inclusion: non_null

也可以自定义ObjectMapper Bean,SpringBoot会自动使用这个Bean来替代默认的ObjectMapper

@Configuration
public class JacksonConfig {  
    @Bean  
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {  
        return builder  
            .serializationInclusion(JsonInclude.Include.NON_NULL) //忽略空值  
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) //禁用时间戳 
            // 可以添加更多的自定义配置  
            .build();  
    }
}

你可能感兴趣的:(spring,java,yml,spring,boot)