注解:
测试代码:
@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; } }