我的 JSON 如下所示:
{
"totalSize": 11,
"done": true,
"records": [
{
"attributes": {
"type": "Team_Member",
"url": "/services/data/Team_Member/xxxx"
},
"Age": 48,
"Birth_Date": "1971-05-17",
"Business": null,
"Citizenship": null,
"Country": "UK",
...other fields...
},
{ other records ....}
]
}
records数组中的对象可以是不同类型的,但不会混合。反序列化时,属性字段可以忽略。
我正在尝试使用 jackson 将其反序列化到这个 Java 类中:
@lombok.Data
public class QueryResult<C extends BaseObject> {
private int totalSize;
private boolean done;
private List<C> records;
}
BaseObject 的子类将具有必需的字段,例如:
public class TeamMember extends BaseObject {
public int Age;
public Date Birth_Date;
//etc...
}
这是反序列化代码:
public <C extends BaseObject> QueryResult<C> doQuery(Class<C> baseObjectClass) {
String json = ...get json from somewhere
ObjectMapper mapper = new ObjectMapper();
try {
JavaType type = mapper.getTypeFactory().constructCollectionLikeType(QueryResult.class, baseObjectClass);
return mapper.readValue(json, type);
} catch (Exception e) {
throw new RuntimeException(e);
}
但这并不成功,我得到了异常:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a Value deserializer for type [collection-like type; class com.foo.QueryResult, contains [simple type, class com.foo.TeamMember]]
如有任何建议,我们将不胜感激。
最佳答案
方法中的第一个参数名称constructCollectionLikeType是 collectionClass
,因此它必须是集合类型:例如 ArrayList
。
您需要使用constructParametricType方法。
JavaType queryType = mapper.getTypeFactory().constructParametricType(QueryResult.class, TeamMember.class);
QueryResult<TeamMember> queryResult = mapper.readValue(jsonFile, queryType);
关于java - 使用 Jackson 进行 JSON 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59427942/