"JSON" Jackson Beginner, and common examples

Source: Internet
Author: User

Many companies now have projects based on the SOA architecture, and there are many ways in which calls are made between systems, and one common use is to return the results in JSON format using the HTTP protocol.

This makes the use of JSON more common. The framework of the processing of JSON in the market is multifarious, the common Jsonobject, Gson, Jackson and so on.

Now we're going to learn about Jackson and record some common examples

> Release Notes
<Dependencies>    <Dependency>        <groupId>Com.fasterxml.jackson.core</groupId>        <Artifactid>Jackson-core</Artifactid>        <version>2.1.4</version>    </Dependency>    <Dependency>        <groupId>Com.fasterxml.jackson.core</groupId>        <Artifactid>Jackson-databind</Artifactid>        <version>2.1.4</version>    </Dependency></Dependencies>

> The simplest example

Converts the Bean object to JSON, which is restored back. (in order to get the date format in the specified format, I specified the date format)

 PackageThe simplest example of com.nicchagil.demo.No001;Importjava.io.IOException;ImportJava.sql.Timestamp;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importorg.junit.Test;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.ObjectMapper; Public classCall {@Test Public voidWritejson ()throwsjsonprocessingexception {objectmapper objectmapper=NewObjectmapper (); Objectmapper.setdateformat (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:SS")); String JSON= Objectmapper.writevalueasstring (NewUser (999, "Nick Huang",NewTimestamp (Calendar.getinstance (). Gettimeinmillis ()));    SYSTEM.OUT.PRINTLN (JSON); } @Test Public voidReadjson ()throwsIOException {String json= "{\" id\ ": 999,\" name\ ": \" Nick huang\ ", \" birthday\ ": \" 2015-10-21 15:45:673\ "}"; Objectmapper Objectmapper=NewObjectmapper (); Objectmapper.setdateformat (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:SS")); User User= Objectmapper.readvalue (JSON, User.class);    SYSTEM.OUT.PRINTLN (user); }}
View Code

A bean type is also required

 PackageThe simplest example of com.nicchagil.demo.No001;ImportJava.sql.Timestamp; Public classUser {PrivateInteger ID; PrivateString name; PrivateTimestamp birthday;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicTimestamp Getbirthday () {returnbirthday; }     Public voidsetbirthday (Timestamp birthday) { This. Birthday =birthday; }     PublicUser (Integer ID, String name, Timestamp birthday) {Super();  This. ID =ID;  This. Name =name;  This. Birthday =birthday; }     PublicUser () {Super(); } @Override PublicString toString () {StringBuilder builder=NewStringBuilder (); Builder.append ("User [id="). Append (ID). Append (", name="). Append (name). Append (", birthday="). Append (Birthday). Append ("]"); returnbuilder.tostring (); }    }
View Code

The log is as follows

{"id": 999, "name": "Nick Huang", "Birthday": "2015-10-22 17:34:318"}user [ID=999, name=nick Huang, birthday= 2015-10-21 15:45:00.673]
View Code

> How to specify the structure of a transformation in the case of generics and collections
 Packagecom.nicchagil.demo.No002 contains generics and sets;Importjava.io.IOException;ImportJava.sql.Timestamp;ImportJava.util.Calendar;ImportJava.util.HashMap;ImportJava.util.Map;Importorg.junit.Test;Importcom.fasterxml.jackson.core.JsonProcessingException;Importcom.fasterxml.jackson.core.type.TypeReference;ImportCom.fasterxml.jackson.databind.ObjectMapper; Public classCall {@Test Public voidWritejson ()throwsjsonprocessingexception {objectmapper objectmapper=NewObjectmapper (); Map<string, object> map =NewHashmap<string, object>(); Map.put ("Nick,"NewUser (999, "Nick Huang",NewTimestamp (Calendar.getinstance (). Gettimeinmillis ())); Map.put ("Robbin",NewUser (998, "Robbin",NewTimestamp (Calendar.getinstance (). Gettimeinmillis ())); String JSON=objectmapper.writevalueasstring (map);    SYSTEM.OUT.PRINTLN (JSON); } @Test Public voidReadjson ()throwsIOException {String json= "{\" robbin\ ": {\" id\ ": 998,\" name\ ": \" robbin\ ", \" birthday\ ": 1445415635096},\" nick\ ": {\" id\ ": 999,\" name\ ": \" Nick Huang\ ", \" birthday\ ": 1445415635096}}"; Objectmapper Objectmapper=NewObjectmapper (); Map<string, user> map = Objectmapper.readvalue (JSON,NewTypereference<map<string, user>>() {});    SYSTEM.OUT.PRINTLN (map); }}
View Code

The log is as follows

{"Robbin": {"id": 998, "name": "Robbin", "Birthday": 1445506610097}, "Nick": {"id": 999, "name": "Nick Huang", "Birthday" : 1445506610097}}{robbin=user [id=998, Name=robbin, birthday=2015-10-21 16:20:35.096], Nick=User [id=999, Name=nick Huang, birthday=2015-10-21 16:20:35.096]}
View Code

> More complex structures

For example, the different key values in the map correspond to different types (I am just the soil method, a good way of the baby boots under the hint OH) (>_<)

 Packagecom.nicchagil.demo.No003 complex structure;Importjava.io.IOException;ImportJava.sql.Timestamp;ImportJava.util.Calendar;ImportJava.util.HashMap;ImportJava.util.Map;Importorg.junit.Test;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.ObjectMapper;Importcom.nicchagil.demo.No001 The simplest example. User; Public classCall {@Test Public voidWritejson ()throwsjsonprocessingexception {objectmapper objectmapper=NewObjectmapper (); Map<string, object> map =NewHashmap<string, object>(); Map.put ("Code", "Success"); Map.put ("Data",NewUser (999, "Nick Huang",NewTimestamp (Calendar.getinstance (). Gettimeinmillis ())); String JSON=objectmapper.writevalueasstring (map);    SYSTEM.OUT.PRINTLN (JSON); } @Test Public voidReadjson ()throwsIOException {String json= "{\" data\ ": {\" id\ ": 999,\" name\ ": \" Nick huang\ ", \" birthday\ ": 1445502596155},\" code\ ": \" Success\ "}"; Objectmapper Objectmapper=NewObjectmapper (); Map<string, object> map = Objectmapper.readvalue (JSON, map.class); Object Data= Map.get ("Data"); User User= Objectmapper.convertvalue (data, User.class); Map.put ("Data", user);                SYSTEM.OUT.PRINTLN (map); /*Print out Type*/System.out.println ("Code ' s Type:" + map.get ("code")). GetClass (). toString ()); System.out.println ("Data ' type:" + map.get ("Data")). GetClass (). toString ()); }}
View Code

The log is as follows

{"Data": {"id": 999, "name": "Nick Huang", "Birthday": 1445506936594}, "code": "Success"}{data=user [id=999, Name=nick Huang, Birthday=2015-10-22 16:29:56.155], code=success}code ' s type:class java.lang.Stringdata ' s The simplest example of Type:class com.nicchagil.demo.No001. User
View Code

"JSON" Jackson Beginner, and common examples

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.