我通过这篇文章学会了如何一起使用Json和java.util.Optional: https://medium.com/@harittweets/how-to-use-java-util-optional-and-json-together-12434f9d55b9#.r0kpo65f8
但是当类的属性是Date类型并且必须格式化时,我遇到了另一个问题。所以我使用@JsonFormat:
timestamps
我使用Spring boot for My App,这是配置:
public class UserBean extends BasicBean {
private String username;
private String password;
@JsonFormat(pattern = "yyyy-MM-dd")
private Optional<Date> dob;
// getter and setter
}
我使用Advanced Rest Client进行测试,配置如下:
结果如下:
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.hag.prj")
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
public class ApplicationConfig {
@Bean
@Primary
public ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder.json().serializationInclusion(JsonInclude.Include.NON_NULL)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.modules(this.jdk8Module(), this.jsrModule(), this.parameterNamesModule()).build();
}
@Bean
public Module jdk8Module() {
final Jdk8Module jdk8Module = new Jdk8Module();
jdk8Module.configureAbsentsAsNulls(true);
return jdk8Module;
}
@Bean
public Module jsrModule() {
return new JavaTimeModule();
}
@Bean
public Module parameterNamesModule() {
return new ParameterNamesModule();
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UserBean> create(UserBean userBean){
return ResponseEntity.ok(userBean);
}
}
我该如何解决这个问题
答案 0 :(得分:0)
尝试:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")