无法将json转换为Model [英] Can not convert json to Model
问题描述
我有来自url的json.我需要将此json转换为模型
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;
}
尝试转换
ObjectMapper mapper = new ObjectMapper();
Dates dates = mapper.readValue(forObject, Response.class);
尝试转换时出现错误:
无法在START_ARRAY之外反序列化packeg.DatesField的实例 令牌
Can not deserialize instance of packeg.DatesField out of START_ARRAY token
推荐答案
根据模型,属性json不正确.在datesField
对象中没有datesField
类型的数组,而是一个字符串数组.
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.
您的对象json等效项应为:
Your object json equivalent shall be:
{
"someField": 3,
"datesField": {
"strings":["2017-08-19",
"2017-08-20",
"2017-08-26",
"2018-12-30"]
}
}
反之,如果您需要适应json响应,请按照@xenteros的建议将模型更改为:
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;
}
此外,请注意,用于映射响应的Java代码应更改为:
Also, note that the java code to map the response should be changed from:
Dates dates = mapper.readValue(forObject, Response.class);
到
Response response = mapper.readValue(forObject, Response.class);
这篇关于无法将json转换为Model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!