SpringBoot整合jackson
作者:互联网
对象配置
注解:
- @JsonProperty
定制属性序列化/反序列化的名称,默认名称是属性名(value为属性名,index为属性的优先级) - @JsonFormat
时间格式化,pattern需要的时间格式,timezone时区 - @JsonIgnore
属性序列化和反序列化中忽略某个属性 - @JsonIgnoreProperties
忽略多个属性,{}中填写多个要忽略的属性名称
测试代码:
@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