jason有一个字符串字段为null,因此Jackson解析器抛出错误

问题描述 投票:0回答:1

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。

rest jackson
1个回答
0
投票

我认为您可以在类上使用以下注释来解决错误:

@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;
© www.soinside.com 2019 - 2024. All rights reserved.