1. Import the Jackson jar
<Dependency> <groupId>Com.fasterxml.jackson.core</groupId> <Artifactid>Jackson-databind</Artifactid> <version>2.8.9</version></Dependency>
2. Java code is as follows
Public classJsonutils {//defining the Jackson object Private Static FinalObjectmapper MAPPER =NewObjectmapper (); /*** Converts an object into a JSON string. * @paramData *@return */ Public StaticString Objecttojson (Object data) {Try{string String=mapper.writevalueasstring (data); returnstring; } Catch(jsonprocessingexception e) {e.printstacktrace (); } return NULL; } /*** Convert JSON result set to Object * *@paramjsondata JSON data *@paramtype of object in the Clazz object *@return */ Public Static<T> T Jsontopojo (String jsondata, class<t>Beantype) { Try{T T=Mapper.readvalue (Jsondata, Beantype); returnT; } Catch(Exception e) {e.printstacktrace (); } return NULL; } /*** Convert JSON data to Pojo object list * <p>Title:jsonToList</p> * <p>description: </p> *
@paramJsondata *@paramBeantype *@return */ Public Static<T>List<T> jsontolist (String jsondata, class<t>Beantype) {Javatype Javatype= Mapper.gettypefactory (). Constructparametrictype (List.class, Beantype); Try{List<T> list =Mapper.readvalue (Jsondata, Javatype); returnlist; } Catch(Exception e) {e.printstacktrace (); } return NULL; } }
Java JSON and Object convert each other