JSON "= = =" JavaBean of mutual conversion

Source: Internet
Author: User
Tags object object tojson
  1. The role and benefits of JSON

in the Javaweb project, the direct interaction between the front and back, interface and so on, basically inseparable from the JSON.

JSON: Full name JAvaScript Object Notation (JavaScript object notation)

JSON is the syntax for storing and exchanging textual information. Similar to XML.

JSON is smaller, faster, and easier to parse than XML

2. Configure Jackson's jar package

1), the quickest way is to add the pom.xml in spring boot

       <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId> jackson-databind</artifactid>            <version>2.8.3</version>        </dependency>               < dependency>            <groupId>commons-lang</groupId>            <artifactid>commons-lang</ Artifactid>            <version>2.6</version>       

2), manual import (not necessarily the same version)

  3. for a more convenient use of JSON, encapsulate it into a Jsonmapper tool class
 Packagecom.djb.common.utils;Importjava.io.IOException;Importorg.apache.commons.lang.StringUtils;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;Importcom.fasterxml.jackson.core.JsonParser.Feature;Importcom.fasterxml.jackson.databind.DeserializationFeature;ImportCom.fasterxml.jackson.databind.JavaType;ImportCom.fasterxml.jackson.databind.ObjectMapper;Importcom.fasterxml.jackson.databind.SerializationFeature;ImportCom.fasterxml.jackson.databind.util.JSONPObject; Public classJsonmapper {Private StaticLog logger = Logfactory.getlog (jsonmapper.class); Private StaticObjectmapper Mapper; Private StaticJsonmapper _instance =NewJsonmapper (); PrivateJsonmapper () {mapper=Getmapper (); Mapper.configure (Serializationfeature.fail_on_empty_beans,false); Mapper.configure (Deserializationfeature.fail_on_unknown_properties,false); Mapper.configure (Deserializationfeature.fail_on_ignored_properties,false); //allow special characters and escape symbols to appearMapper.configure (Feature.allow_unquoted_control_chars,true); //allow single quotes to appearMapper.configure (Feature.allow_single_quotes,true); }  /*** Returns NULL if the JSON string is null or a "null" string. Returns an empty collection if the JSON string is "[]".   * * If you want to read a collection such as List/map, and not list<string> this simple type, use the following statement to use the function on the back side. */   Public<T> T Fromjson (String jsonstring, class<t>clazz) {    if(Stringutils.isempty (jsonstring)) {return NULL; }    Try {      returnMapper.readvalue (jsonstring, clazz); } Catch(IOException e) {Logger.warn ("Parse JSON string error:" +jsonstring, E); return NULL; }  }  /*** Returns NULL if the JSON string is null or a "null" string. Returns an empty collection if the JSON string is "[]". * * If you want to read a collection such as List/map, and not list<string>, * first constructs javateype with Constructparametrictype (List.class,mybean.class),   Call this function again. */@SuppressWarnings ("Unchecked")   Public<T>T Fromjson (String jsonstring, Javatype javatype) {if(Stringutils.isempty (jsonstring)) {return NULL; }    Try {      return(T) mapper.readvalue (jsonstring, Javatype); } Catch(IOException e) {Logger.warn ("Parse JSON string error:" +jsonstring, E); return NULL; }  }  /*** Constructs a generic type such as List<mybean>, map<string,mybean>*/   PublicJavatype Constructparametrictype (class<?> parametrized, class<?>... parameterclasses) {    returnmapper.gettypefactory (). Constructparametrictype (parametrized, parameterclasses); }  /*** returns "NULL" if the object is null. Returns "[]" if the collection is an empty collection. */   PublicString ToJson (Object object) {Try {      returnmapper.writevalueasstring (object); } Catch(IOException e) {Logger.warn ("Write to JSON string error:" +object, E); return NULL; }  }  /*** Output JSONP format data. */   Publicstring Tojsonp (string functionname, Object object) {returnToJson (NewJsonpobject (functionname, object)); }  /*** Remove Mapper to make further settings or use other serialization APIs. */   Public Staticobjectmapper Getmapper () {if(Mapper = =NULL) {Mapper=NewObjectmapper (); }    returnmapper; }  /*** Get Instance * *@return   */   Public StaticJsonmapper getinstance () {return_instance; }}
4, the next can be tested.
 PackageCOM.LRJ;ImportJava.util.Map;ImportCom.lrj.bean.Developer;ImportCom.lrj.common.JsonMapper; Public classTest01 { Public Static voidMain (string[] args) {Developer Developer=NewDeveloper (); Developer.setname ("Jack"); Developer.setage (22); Developer.setdept ("IT");
Developer.setsaraly (8000D); Developer.setaddress ("Blog Park"); //for a complex list, convert to a map collection and then to an objectString jsonstr = "{\" developer\ ": \" {\\\ "name\\\": \\\ "jack\\\", \\\ "age\\\": 22,\\\ "saraly\\\": 8000.0,\\\ "address\\\ ": \\\" blog Park \\\ ", \\\" dept\\\ ": \\\" it\\\ "}\", \ "Other\": null} "; Map<string, object> map = Jsonmapper.getinstance (). Fromjson (Jsonstr, map.class); String Beanstr= Map.get ("developer") + ""; Developer Developer3= Jsonmapper.getinstance (). Fromjson (Beanstr, Developer.class); System.out.println (DEVELOPER3); String jsonstring=jsonmapper.getinstance (). ToJson (developer); System.out.println (jsonstring); Developer Developer2= Jsonmapper.getinstance (). Fromjson (jsonstring, Developer.class); System.out.println (DEVELOPER2); }}
5, test JSON is legitimate, has converted the JSON into the entity class of the website

http://www.bejson.com/json2javapojo/new/

When a JSON conversion exception is encountered, debug or output the JSON string and copy to the Web site test to help troubleshoot the error.

Note: The JSON conversion is not a simple list<string> that JS object contains other objects, in the Java entity class, is a class containing other classes,

At this point, you have to convert the JSON to map<string, Object>, and then take out the objects you want to convert to an entity class.

For example:

    map<string, object> map = jsonmapper.getinstance (). Fromjson (Jsonstr, map. class );   = Map.get ("Bean") + "";     if (Utilpublic.notempty (pickup)) {          = jsonmapper.getinstance (). Fromjson (Bean, bean. class);
}

6. PostScript

There are many want to write down, but did not write, not what busy, is their lazy, think, this to get a bit, at least a few or a few hours.

Forwarding please indicate the source www.cnblogs.com/lrj1009IRET/p/9454728.html, thank you!

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.