简体   繁体   中英

Can not convert json to Model

I have json from url. I need Convert This json to Model

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

I create models for mapping

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

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

try convert

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

I get error when try convert:

Can not deserialize instance of packeg.DatesField out of START_ARRAY token

The json attributed is incorrect according to the model. There is no array of datesField type but an array of strings within the datesField object.

Your object json equivalent shall be:

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

Or the other way, if you need to adapt to the json response, change your model as suggested by @xenteros to:

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

Also, note that the java code to map the response should be changed from:

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

to

Response response = mapper.readValue(forObject, Response.class);
{
    "someField": 3,
    "datesField": ["2017-08-19",
    "2017-08-20",
    "2017-08-26",
    "2018-12-30"]
}

is equivalent to

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

You should rather parse the following json :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM