您的问题不在于 JSON 中传递了 null 值。问题是 JSON 包含一个具有值的字符串"NULL"
.
因此,为了解决这个问题,有许多可用的方法。我认为以下两个适用于这种情况。
替代方案 1:修复 JSON
第一个替代方案是修复 JSON,使其不包含字符串值"NULL"
并包含值null
(未引用)或直接跳过它。
想象一下以下 POJO:
public class DatePojo {
@JsonInclude(value= JsonInclude.Include.NON_EMPTY)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MMM-yyyy", timezone="PST")
@JsonProperty("date")
private Date date;
}
以下测试显示有效日期、空值和null
价值观工作:
@Test
public void testJson() throws IOException {
String jsonWithValidDate = "{\"date\":\"12-Jun-1982\"}";
String jsonWithNoDate = "{}";
String jsonWithNullDate = "{\"date\":null}";
ObjectMapper mapper = new ObjectMapper();
final DatePojo pojoWithValidDate = mapper.readValue(jsonWithValidDate, DatePojo.class);
final DatePojo pojoWithNoDate = mapper.readValue(jsonWithNoDate, DatePojo.class);
final DatePojo pojoWithNullDate = mapper.readValue(jsonWithNullDate, DatePojo.class);
Assert.assertNotNull(pojoWithValidDate.date);
Assert.assertNull(pojoWithNoDate.date);
Assert.assertNull(pojoWithNullDate.date);
}
但是,如果您传递该值"NULL"
测试失败,因为"NULL"
无法解析为日期:
@Test(expected = JsonMappingException.class)
public void testInvalidJson() throws IOException {
String jsonWithNullString = "{\"date\":\"NULL\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonWithNullString, DatePojo.class); // Throws the exception
Assert.fail();
}
替代方案 2:提供您自己的转换器来处理"NULL"
如果无法修复 JSON(如替代方案 1 中所述),您可以提供自己的转换器。
像这样设置你的 pojo:
public class DatePojo {
@JsonProperty("date")
@JsonDeserialize(converter = MyDateConverter.class)
private Date date;
}
并提供一个转换器,如下所示:
public class MyDateConverter extends StdConverter<String, Date> {
@Override
public Date convert(final String value) {
if (value == null || value.equals("NULL")) {
return null;
}
try {
return new SimpleDateFormat("dd-MMM-yyyy").parse(value);
} catch (ParseException e) {
throw new IllegalStateException("Unable to parse date", e);
}
}
}
那么,你应该已经准备好了。以下测试通过:
@Test
public void testJson() throws IOException {
String jsonWithValidDate = "{\"date\":\"12-Jun-1982\"}";
String jsonWithNoDate = "{}";
String jsonWithNullDate = "{\"date\":null}";
String jsonWithNullString = "{\"date\":\"NULL\"}"; // "NULL"
ObjectMapper mapper = new ObjectMapper();
final DatePojo pojoWithValidDate = mapper.readValue(jsonWithValidDate, DatePojo.class);
final DatePojo pojoWithNoDate = mapper.readValue(jsonWithNoDate, DatePojo.class);
final DatePojo pojoWithNullDate = mapper.readValue(jsonWithNullDate, DatePojo.class);
final DatePojo pojoWithNullStr = mapper.readValue(jsonWithNullString, DatePojo.class); // Works
Assert.assertNotNull(pojoWithValidDate.date);
Assert.assertNull(pojoWithNoDate.date);
Assert.assertNull(pojoWithNullDate.date);
Assert.assertNull(pojoWithNullStr.date); // Works
}
IMO,最好的方法是使用替代方案 1,只需更改 JSON。