How Jackson implements a conversion between a JSON string and a generic list collection

Source: Internet
Author: User

Objective:

Jackson Common methods:

Jackson is the usual two ways to handle the conversion between generic Java objects and JSON are the writevalueasstring () and ReadValue () methods of the Objectmapper class that can be implemented.

However, if it is to be turned into a list collection of the specified generics, such as list<user>. You need to deserialize the complex type to generics first

Collection Type;

To illustrate:

If it is a list<user> collection, then use Objectmapper's gettypefactory (). Constructparametrictype (List.class, User.class);

If it is a hashmap<string,user> collection, then use Objectmapper's gettypefactory (). Constructparametrictype (HashMap.class, String.class,user. Class);

code implementation:

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);     }          /**            *  get collection type    of generics        *  @param  collectionClass  Generics collection            *  @param  elementClasses  Element Classes             *  @return  javatype java Type             *  @since  1.0            */       public static javatype getcollectiontype ( class<?> collectionclass, class<?>... elementclasses)  {            return mapper.gettypefactory (). ConstructParametricType ( collectionclass, elementclasses);        }


This article is from the "Simple Life" blog, so be sure to keep this source http://simplelife.blog.51cto.com/9954761/1704106

How Jackson implements a conversion between a JSON string and a generic list collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.