我对 Jackson 将 json 文件反序列化为 poco 存在误解。这是我的代码:
JsonParser jp = new JsonFactory().createJsonParser(new File(pathFile));
ObjectMapper objectMapper = new ObjectMapper();
MappingIterator<AnimalBean> animalsss = objectMapper.readValues(jp, AnimalBean.class);
while (animalsss.hasNext())
{
AnimalBean abba = animalsss.next();
System.out.println(abba.getNom());
}
我的 POCO 名为 AnimalBean :
public class AnimalBean
{
private String id;
private String nom;
private String nom_scientifique;
private String classe;
private String ordre;
private String famille;
private String details_zone;
private String poids;
private String duree_gestation;
private String nb_gestation;
private String longevite;
private String description;
private String images;
... + all getter/setter
} 还有我的 JSON 文件:
{
"zoo": {
"animaux": {
"animal": [{
"id": 1,
"nom": "test",
"nom_scientifique": "test2",
"classe": 1,
"ordre": 3,
"famille": 4,
"details_zone": "Zones",
"poids": "80",
"duree_gestation": "11",
"nb_gestation": "1",
"longevite": "25 ans",
"description": "texte de description"
}]
}
}
}
当我执行代码时,出现以下错误:无法识别的字段“zoo”(AnimalBean 类),未标记为可忽略。我知道问题是我的 json 文件不是直接由动物开始的,但我无法更改它,因为它不是我的。我已经尝试将 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);但它改变了一切。
有人可以帮助我吗?
最佳答案
为什么不直接使用几个包装类来匹配 JSON?
喜欢:
public class Wrapper {
public Zoo zoo;
}
public class Zoo {
public Animals animaux;
}
public class Animals {
public Animal[] animal;
}
然后绑定(bind):
Wrapper w = mapper.readValue(json, Wrapper.class);
for (Animal animal : w.zoo.animaux.animal) {
// process!
}
关于java - 反序列化映射 Jackson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664957/