我需要将Json反序列化为JUnit中的Java对象。 我的Json文件如下
{
"studentId":57,
"JoinedDate":"31-12-2019",
"DOB":"08-06-1998"
}
我也有同样的课要做地图
public class Student{
private long studentId ;
private LocalDate JoinedDate;
private LocalDate DOB ;
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public LocalDate getJoinedDate() {
return JoinedDate;
}
public void setJoinedDate(LocalDate joinedDate) {
JoinedDate = joinedDate;
}
public LocalDate getDOB() {
return DOB;
}
public void setDOB(LocalDate dOB) {
DOB = dOB;
}
我需要为类似这样的单元测试项目编写集中式构建器
builder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
单元测试项目看起来像
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class StudentTest{
private ObjectMapper jsonObjectMapper;
@Before
public void setUp() throws IOException {
jsonObjectMapper = new ObjectMapper();
studentJson = IOUtils.toString(getClass().getResourceAsStream(CommonTestConstants.StudentPath+ "/Student.json"));
}
映射对象时出错-com.fasterXml.jackson.databind.exc.InvalidFormatException:无法从字符串“31-12-2019”反序列化java.time.LocalDate
类型的值:无法反序列化java.time.LocalDate:
另一个错误--有时候。
com.fasterXml.jackson.databind.JsonMappingException:无法分析索引%0处的文本“31-12-2019”
我认为LocalDate格式不匹配是问题所在。 任何建议,使其集中的方式,而不是指定格式以上的字段。 有谁能建议一下吗?
引用-Spring BootJacksonTester自定义序列化程序未注册
您只需指定日期格式,默认情况下,jackson允许的格式为yyyy-MM-dd
public class Student{
private long studentId ;
@JsonProperty("JoinedDate") @JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate JoinedDate;
@JsonProperty("DOB") @JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate DOB ;
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public LocalDate getJoinedDate() {
return JoinedDate;
}
public void setJoinedDate(LocalDate joinedDate) {
this.JoinedDate = joinedDate;
}
public LocalDate getDOB() {
return DOB;
}
public void setDOB(LocalDate dOB) {
this.DOB = dOB;
}
我希望对你有帮助
springboot1.4.x
或更高版本具有此界面Jackson2ObjectMapperBuilderCustomizer
,它允许您初始化ObjectMapper
。
我们需要做的是覆盖自定义
方法并注册反序列化器
和序列化器
。
Class TestApplication implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
// pattern could be anything whatever is required
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/dd/MM");
LocalDateSerializer localDateDeserializer = new LocalDateSerializer(formatter);
jackson2ObjectMapperBuilder
.failOnEmptyBeans(false)
.deserializersByType(new HashMap<Class<?>, JsonDeserializer<?>>(){{
put(LocalTime.class, localTimeSerializer);
}});
}
}
我们也可以用类似的方式添加seriliazers
。
jackson2ObjectMapperBuilder
.failOnEmptyBeans(false)
.serializersByType(new HashMap<Class<?>, JsonSerializer<?>>(){{
put(LocalTime.class, localTimeSerializer);
}});
你可以在这里查看更多细节。 spring·jackson建筑商