REST API返回的JSON字符串为{\“Id \”:1,\“Name \”:\“Test1 \”,\“Description \”:\“Test1 description \”,\“ShowInMainScreen \”:true,\ “CREATEDATE \”:\ “2017-12-09T09:55:37 \”,\ “LASTUPDATEDATE \”:\ “2017-12-09T09:55:37 \”,\ “TrainingsCategories \”:空}
我对应的Java对象是
public class TrainingData {
@JsonProperty("Id")
private int Id;
@JsonProperty("Name")
private String Name;
@JsonProperty("Description")
private String Description;
@JsonProperty("ShowInMainScreen")
private boolean ShowInMainScreen;
@JsonProperty("CreateDate")
private String CreateDate;
@JsonProperty("LastUpdateDate")
private String LastUpdateDate;
@JsonProperty("TrainingsCategories")
private String TrainingsCategories;
以下代码返回错误
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
trainingList = mapper.readValue(jsonStringNew, new TypeReference<List<TrainingData>>(){});
返回错误是因为TrainingsCategories具有null值。如果null是双引号,那么一切正常。但REST API不会返回带双引号的null。
我认为您可以在类上使用以下注释来解决错误:
@JsonInclude(JsonInclude.Include.NON_NULL)
以我的一个java类为例,我可以在json字段中使用null值。
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Module {
@JsonProperty("name")
@XmlElement(name="name")
private String name = null;