类似于 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/