如何使用jackson反序列化的对象数组

jackson的数据绑定文档表明,jackson支持反序列化“所有支持types的数组”,但我无法弄清楚这个确切的语法。

对于单个对象,我会这样做:

//json input { "id" : "junk", "stuff" : "things" } //Java MyClass instance = objectMapper.readValue(json, MyClass.class); 

现在对于一个数组我想这样做:

 //json input [{ "id" : "junk", "stuff" : "things" }, { "id" : "spam", "stuff" : "eggs" }] //Java List<MyClass> entries = ? 

任何人都知道是否有一个神奇的失踪命令? 如果不是,那么解决scheme是什么?

首先创build一个映射器:

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

作为数组:

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

列表:

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

指定列表types的另一种方法是:

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

从尤金Tskhovrebov

 List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class)) 

这个解决scheme似乎对我来说是最好的

对于通用实现:

 public static <T> List<T> parseJsonArray(String json, Class<T> classOnWhichArrayIsDefined) throws IOException, ClassNotFoundException { ObjectMapper mapper = new ObjectMapper(); Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";"); T[] objects = mapper.readValue(json, arrayClass); return Arrays.asList(objects); } 
 try { ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); List<User> lstUser = null; JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json")); TypeReference<List<User>> tRef = new TypeReference<List<User>>() {}; lstUser = mapper.readValue(jp, tRef); for (User user : lstUser) { System.out.println(user.toString()); } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

首先创build一个线程安全的ObjectReader实例。

 ObjectMapper objectMapper = new ObjectMapper(); ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){}); 

然后使用它:

 List<MyClass> result = objectReader.readValue(inputStream);