无法将json转换为Model

时间:2017-08-18 15:01:00

标签: java json jackson

我有来自url的json。我需要将此json转换为Model

{
    "someField": 3,
    "datesField": ["2017-08-19",
    "2017-08-20",
    "2017-08-26",
    "2018-12-30"]
}

我创建了用于映射的模型

@Data
@NoArgsConstructor
private class Response{
    @JsonProperty("someField")
    private int someField;
    @JsonProperty("datesField")
    private DatesField datesField;
}

@Data
@NoArgsConstructor
private class DatesField{
    private String[] strings;
}

尝试转换

ObjectMapper mapper = new ObjectMapper();
Dates dates = mapper.readValue(forObject, Response.class);

尝试转换时出错:

  

无法从START_ARRAY反序列化packeg.DatesField的实例   令牌

2 个答案:

答案 0 :(得分:3)

根据模型,json归因于错误。没有datesField类型的数组,而是datesField对象中的字符串数组。

您的对象json等效值应为:

{
    "someField": 3,
    "datesField": {
        "strings":["2017-08-19",
         "2017-08-20",
         "2017-08-26",
         "2018-12-30"]
     }
}

或者另一方面,如果您需要适应json响应,请按照@xenteros的建议将模型更改为:

@Data
@NoArgsConstructor
private class Response{
    @JsonProperty("someField")
    private int someField;
    @JsonProperty("datesField")
    private String[] datesField;
}

另请注意,应该更改映射响应的java代码:

Dates dates = mapper.readValue(forObject, Response.class);

Response response = mapper.readValue(forObject, Response.class);

答案 1 :(得分:0)

{
    "someField": 3,
    "datesField": ["2017-08-19",
    "2017-08-20",
    "2017-08-26",
    "2018-12-30"]
}

相当于

@Data
@NoArgsConstructor
private class Response{
    @JsonProperty("someField")
    private int someField;
    @JsonProperty("datesField")
    private String[] datesField;
}

您应该解析以下json

{
    "someField": 3,
    "datesField": {
         "strings":
            ["2017-08-19",
            "2017-08-20",
            "2017-08-26",
            "2018-12-30"]
        }
}