java - 使用 Jackson 进行 JSON 反序列化

标签 java json jackson

我的 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]]

如有任何建议,我们将不胜感激。

最佳答案

方法中的第一个参数名称constructCollectionLikeTypecollectionClass,因此它必须是集合类型:例如 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/

相关文章:

java - 是否可以将正则表达式简化为匹配?

javascript - Chartist 的饼图标签放错位置,我无法调试它

java - 以日期或原语作为参数的 Jersey Web 服务

java - 使用 Jackson 操作 JSON 的一部分

java - JsonGenerationException : CSV generator does not support Object values for properties

java - 链表 : definition of . 下一个和临时链表节点

java - 无法转换为org.springframework.security.core.userdetails.UserDetails,根本原因是Java spring-boot security错误

java - 在许多 pentaho prpt 报告之间共享外观和感觉

php - 将数组作为数组而不是 PHP 中的 JSON 传递给 javascript

json - Django Cors 允许访问控制允许 header