其他分享
首页 > 其他分享> > SpringBoot整合jackson

SpringBoot整合jackson

作者:互联网

对象配置

注解:

测试代码:

@JsonIgnoreProperties({"address","age"})
public class User {
    //制定属性序列化/反序列化的名称,默认名称是属性名
    @JsonProperty(value = "hello",index = 10)
    private String username;
    @JsonProperty(index = 9)
    private Integer age;
    @JsonProperty(index = 8)
    private String address;
    //@JsonProperty(index = 7)
    //序列化/反序列化时忽略属性
    //@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai")
    //类似于@JsonProperty中的index
    //@JsonPropertyOrder()
    //@JsonIgnore
    private Date birthday;
@RestController
public class UserController {
    @GetMapping("/user")
    public User getUser(){
        User user = new User();
        user.setAddress("jingxiuyaun");
        user.setAge(12);
        user.setUsername("haha");
        user.setBirthday(new Date());
        return user;
    }
}

反序列化:

@RestController
public class UserController {
    @PostMapping("/user")
    public void getreturnUser(@RequestBody User user){
        System.out.println(user);
    }
}

在这里插入图片描述

全局配置

通过ObjectMapping来配置所有的属性,重写JacksonAutoConfiguration类中的方法

@Bean
		@Primary
		@ConditionalOnMissingBean
		ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
			return builder.createXmlMapper(false).build();
		}
@Configuration
public class WebMvcConfig {
    @Bean
    ObjectMapper mapper(){
        ObjectMapper om = new ObjectMapper();
        om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return om;
    }
}

标签:JsonProperty,jackson,SpringBoot,index,user,整合,序列化,public,属性
来源: https://blog.csdn.net/m0_46635265/article/details/123058411