java - 使用自定义构造函数将 JsonNode 转换为 POJO

标签 java json playframework jackson

类似于 Convert JsonNode into POJO
Converting JsonNode to java array但无法找到我的问题的确切解决方案。

这是我的 POJO 声明:

public class Building implements Serializable {

    private BuildingTypes type;

    public Building(BuildingTypes type) {
        this.type = type;
    }

    public BuildingTypes getType() {
        return type;
    }   
}

public enum BuildingTypes {
    TRIPLEX, DUPLEX, HOUSE
}

因此,在我的测试中,我想获取建筑物列表并将 json 列表转换/绑定(bind)到真实对象构建列表。

这就是我想要做的:
Result result = applicationController.listLatestRecords();
String json = contentAsString(result);
JsonNode jsonNode = Json.parse(json);

List<Building> buildings = new ArrayList<>();

buildings.add(mapper.treeToValue(jsonNode.get(0), Building.class));

但是,我收到以下错误:
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class domain.building.Building]: can not instantiate from JSON object (need to add/enable type information?)

显然,如果我在 Building 类中删除我的构造函数并为我的字段类型添加一个 setter,它就可以工作。但是,如果我确实有一个要求迫使我避免使用 setter 等,是否必须使用构造函数来初始化类型值?如何轻松地将 json 绑定(bind)/转换为建筑物列表?

我也尝试了以下但没有成功:
List<Building> buildings = mapper.readValue(contentAsString(result),
            new TypeReference<List<Building>>() {});

最佳答案

错误消息说明了一切,您的 Building类没有默认构造函数,因此 jackson 无法创建它的实例。

Building 中添加默认构造函数类(class)

public class Building implements Serializable {
    private BuildingTypes type;

    public Building(BuildingTypes type) {
        this.type = type;
    }

    // Added Constructor 
    public Building() {
    }

    public BuildingTypes getType() {
        return type;
    }   
}

关于java - 使用自定义构造函数将 JsonNode 转换为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026526/

相关文章:

java - 通知客户新创建的 itemId 的最佳实践

ruby - 没有要加载的文件 -- json (LoadError)

java - 重新附加未执行 SQL 查询的分离实体

java - 为什么这个 org.hibernate.exception.GenericJDBCException : could not update occurs only on the remote (virtual) server

java - 无法解析位置/'资源/

java - 将 native 查询移至 NamedNativeQuery 后,位置 [1] 的参数不存在?

javascript - Angular ng-repeat 显示对象项

ajax - 发送Json到nodejs服务器

java - Play Framework : Call Controller/URL from within a Job

java - 在play框架中调用webservice时出现NullPointer异常