How to use Jackson to deserialise an array of objects

前端 未结 8 1291
梦谈多话
梦谈多话 2020-11-21 22:58

The Jackson data binding documentation indicates that Jackson supports deserialising \"Arrays of all supported types\" but I can\'t figure out the exact syntax for this.

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 23:08

    First create a mapper :

    import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
    ObjectMapper mapper = new ObjectMapper();
    

    As Array:

    MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
    

    As List:

    List myObjects = mapper.readValue(jsonInput, new TypeReference>(){});
    

    Another way to specify the List type:

    List myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
    

提交回复
热议问题