Home  >  Article  >  Java  >  Java's Jackson converts json string into generic List

Java's Jackson converts json string into generic List

高洛峰
高洛峰Original
2017-02-16 16:50:261366browse

Jackson, I feel, is the fastest framework for converting between Java and Json. Of course, Google's Gson is also very good, but based on the performance tests of people on the Internet, it seems that Jackson is faster.

Jackson can handle the conversion between general JavaBean and Json by simply using the readValue and writeValueAsString methods of the ObjectMapper object. But if you want to convert a complex type Collection such as List6f9a1a6711dbe2504e0d3824080f2898, you need to first deserialize the complex type into a generic Collection Type.

If it is ArrayList6f9a1a6711dbe2504e0d3824080f2898, then use ObjectMapper’s getTypeFactory().constructParametricType(collectionClass, elementClasses);

If it is HashMapf06a8c1c72a64d06223d9867f08acdf6, then ObjectMapper’s 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); 
}
 
  /**  
  * 获取泛型的Collection Type 
  * @param collectionClass 泛型的Collection  
  * @param elementClasses 元素类  
  * @return JavaType Java类型  
  * @since 1.0  
  */ 
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {  
  return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);  
}

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to Java's Jackson converting json strings into generic Lists, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn