【发布时间】:2014-07-03 20:33:47
【问题描述】:
我有一个 POJO,例如
public class Category {
public Collection<Item> items;
public static class Item {
public String firstAttribute;
public int value;
}
}
我正在使用以下内容从 json 输入转换为 POJO(Category):
JsonNode results = mapper.readTree(connection.getInputStream());
mapper.convertValue(results, Category.class));
这一切都很好,并且按预期工作。但是,输入 JSON 偶尔会包含布尔值 false 而不是实际的项目对象。 JSON 类似于以下内容:
{
"id":1,
"items": [
{
"firstAttribute": "Test 1",
"value": 1
},
{
"firstAttribute": "Test 2",
"value": 2
},
{
"firstAttribute": "Test 3",
"value": 3
},
false,
false,
false,
{
"firstAttribute": "Test 4",
"value": 4
},
false,
{
"firstAttribute": "Test 5",
"value": 5
},
]
}
布尔值抛出解析器,使其抛出异常
java.lang.IllegalArgumentException: Can not instantiate value of type [simple type, class com.example.test.Category$Item] from JSON boolean value; no single-boolean/Boolean-arg constructor/factory method
我试图通过使用@JsonCreator 来解决这个问题
public class Category {
public int id;
public Collection<Item> items;
public static class Item {
public String firstAttribute;
public int value;
@JsonCreator public static Item Parse(JsonNode node) {
if (node.isBoolean()) {
return null;
}
else {
// use default Jackson parsing, as if the method 'Parse' wasn't there
}
}
}
}
这几乎就是我卡住的地方。我一直无法弄清楚如何调用默认的 Jackson Deserializer,.当然,我可以自己简单地检索和设置值,但是,在我正在构建的实际项目中,有大量复杂的模型,以及各种不一致的 json 输入,我宁愿避免解析所有内容手动。
【问题讨论】: