Jackson deserializes the generic list (using Javatype to convert the JSON string to a generic list)

Source: Internet
Author: User

New= "[{\" name\ ": \" A\ ", \" password\ ": \" 345\ "},{\" name\ ": \" b\ ", \" password\ ": \" 123\ "}]";         // The first of these methods New Typereference<list<user>> () {/**/});        The second method Javatype Javatype = Mapper.gettypefactory (). Constructcollectiontype (List.class, User.class); List<user> List2 = Mapper.readvalue (JSON, javatype);

Jackson, I feel like the fastest framework for converting between Java and JSON, and of course Google's Gson is good, but it looks like Jackson's faster than anyone else's performance test on the web.

Jackson handles the conversion between the general JavaBean and JSON as long as the ReadValue and writevalueasstring two methods using the Objectmapper object can be implemented. However, if you want to convert a complex type collection such as List<yourbean>, then you need to deserialize the collection type that is a generic of complex types.

If it is arraylist<yourbean> then use Objectmapper's Gettypefactory (). Constructparametrictype (Collectionclass, elementclasses);

If it is hashmap<string,yourbean> then Objectmapper gettypefactory (). Constructparametrictype (HashMap.class, String.class, Yourbean.class);

 Public FinalObjectmapper mapper =NewObjectmapper ();  Public Static voidMain (string[] args)throwsexception{javatype Javatype= Getcollectiontype (ArrayList.class, Yourbean.class); List<YourBean> LST = (list<yourbean>) Mapper.readvalue (jsonstring, Javatype); }          /*** Gets the collection type of the generic type *@paramcollectionclass Generic Collection *@paramelementclasses Element class *@returnjavatype Java Type *@since1.0*/        Public StaticJavatype Getcollectiontype (class<?> collectionclass, class<?>... elementclasses) {           returnmapper.gettypefactory (). Constructparametrictype (Collectionclass, elementclasses); }

Jackson deserializes the generic list (using Javatype to convert the JSON string to a generic list)

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.