java's Jackson converts the json string to the generic List

  • 2020-06-03 06:32:16
  • OfStack

Jackson, Which I feel is the fastest framework for converting between Java and Json, of course Google's Gson is pretty good too, but according to some performance tests online, it looks like Jackson is 1 o 'clock faster

Jackson handles 1-like conversions between JavaBean and Json using only the readValue and writeValueAsString methods of the ObjectMapper object. But if you want to convert a complex type Collection like List < YourBean > , you need to deserialize Collection Type of the complex type generic first.

If it is ArrayList < YourBean > Then use getTypeFactory() for ObjectMapper.constructParametricType(collectionClass, elementClasses);

If it is HashMap < String,YourBean > So ObjectMapper getTypeFactory (). constructParametricType (HashMap. class, String. class, YourBean class);


  public final ObjectMapper mapper = new ObjectMapper(); 
   
  public static void main(String[] args) throws Exception{ 
    JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); 
    List<YourBean> lst = (List<YourBean>)mapper.readValue(jsonString, javaType); 
  }
  
    /**  
    *  Gets generic Collection Type 
    * @param collectionClass  The generic Collection  
    * @param elementClasses  Element class   
    * @return JavaType Java type   
    * @since 1.0  
    */  
  public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {  
    return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);  
  }


Related articles: