有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

类似于Convert JsonNode into POJOConverting 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列表转换/绑定到一个真实对象建筑物列表

以下是我想做的:

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轻松绑定/转换为建筑物列表

我还尝试了以下方法,但没有成功:

List<Building> buildings = mapper.readValue(contentAsString(result),
            new TypeReference<List<Building>>() {});

共 (1) 个答案

  1. # 1 楼答案

    错误消息表明,您的Building类没有默认构造函数,因此Jackson无法创建它的实例

    Building类中添加默认构造函数

    public class Building implements Serializable {
        private BuildingTypes type;
    
        public Building(BuildingTypes type) {
            this.type = type;
        }
    
        // Added Constructor 
        public Building() {
        }
    
        public BuildingTypes getType() {
            return type;
        }   
    }