反映杰克逊的映射

时间:2012-12-01 23:46:20

标签: java serialization 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);但它改变了一切。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

为什么不使用几个包装类来匹配JSON?

像:

public class Wrapper {
  public Zoo zoo;
}
public class Zoo {
  public Animals animaux;
}
public class Animals {
  public Animal[] animal;
}

然后绑定:

Wrapper w = mapper.readValue(json, Wrapper.class);
for (Animal animal : w.zoo.animaux.animal) {
   // process!
}

答案 1 :(得分:0)

这是完全未经测试的代码,因为我无法准确复制您的情况/代码。基本上它试图将值作为String并进行一些展开,然后创建另一个JsonParser。

ObjectMapper objectMapper = new ObjectMapper();
JsonParser jp = new JsonFactory().createJsonParser(new File(pathFile)); 
String json = jp.getText();
JsonNode node = objectMapper.readTree(json).get("Animal");
JsonParser jp2 = new JsonFactory().createJsonParser(node.getTextValue());

MappingIterator<AnimalBean> animalsss = objectMapper.readValues(jp2, AnimalBean.class);
while (animalsss.hasNext())
{
    AnimalBean abba = animalsss.next();
    System.out.println(abba.getNom());
}