JSON serialization and deserialization with Jackson under Java

Source: Internet
Author: User
Tags dateformat

The common JSON libraries under Java are Gson, Json-lib, and Jackson, and Jackson is relatively efficient, using Jackson for JSON and Java object transformations in the project, with some of Jackson's JSON operations described below.

First, the preparatory work

First go to the official website to download the Jackson Toolkit, Http://wiki.fasterxml.com/JacksonDownload. Jackson has 1.x series and 2.x series, the latest version of the current 2.x series is the 2.9.0,2.x series has 3 jar packages to download:

Jackson-core-2.2.3.jar (Core jar package,)

Jackson-annotations-2.2.3.jar (This package provides JSON annotation support,)

Jackson-databind-2.2.3.jar ()

You can use MAVEN quick dependencies to introduce:

<!--Https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -<Dependency>    <groupId>Com.fasterxml.jackson.core</groupId>    <Artifactid>Jackson-databind</Artifactid>    <version>2.9.0</version></Dependency><!--https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -<Dependency>    <groupId>Com.fasterxml.jackson.core</groupId>    <Artifactid>Jackson-annotations</Artifactid>    <version>2.9.0</version></Dependency><!--Https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -<Dependency>    <groupId>Com.fasterxml.jackson.core</groupId>    <Artifactid>Jackson-core</Artifactid>    <version>2.9.0</version></Dependency>

To prepare the serialized class:

//the user class used by JSON serialization and deserializationImportjava.util.Date;  Public classUser {PrivateString name; PrivateInteger age; PrivateDate birthday; PrivateString Email;  PublicString GetName () {returnname; }       Public voidsetName (String name) { This. Name =name; }             PublicInteger getage () {returnAge ; }       Public voidsetage (Integer age) { This. Age =Age ; }             PublicDate Getbirthday () {returnbirthday; }       Public voidsetbirthday (Date birthday) { This. Birthday =birthday; }             PublicString Getemail () {returnemail; }       Public voidsetemail (String email) { This. email =email; }  }  

Second, Java object to JSON string [JSON serialization]

Importjava.io.IOException; Importjava.text.ParseException; ImportJava.text.SimpleDateFormat; ImportCom.fasterxml.jackson.databind.ObjectMapper;  Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, ioexception {User User=NewUser (); User.setname (Wang); User.setemail ("[Email protected]"); User.setage (20); SimpleDateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd"); User.setbirthday (Dateformat.parse ("1996-10-01")); /*** Objectmapper is the core of JSON operations, and all of Jackson's JSON operations are implemented in Objectmapper.          * Objectmapper has multiple JSON serialization methods that can store JSON strings in different media such as file, OutputStream, and so on.          * WriteValue (file arg0, Object arg1) turns arg1 into a JSON sequence and saves it in a arg0 file.          * WriteValue (OutputStream arg0, Object arg1) turns arg1 into a JSON sequence and saves it in the arg0 output stream.          * Writevalueasbytes (Object arg0) turns the arg0 into a JSON sequence and outputs the result into a byte array.          * Writevalueasstring (Object arg0) turns the arg0 into a JSON sequence and outputs the result as a string. */Objectmapper Mapper=NewObjectmapper (); //user class to JSON//output: {"name": "Wang", "Age": "Birthday": 844099200000, "email": "[email protected]"}String JSON =mapper.writevalueasstring (user);                    SYSTEM.OUT.PRINTLN (JSON); //Java Collection goto JSON//output: [{"Name": "Wang", "Age": "Birthday": 844099200000, "email": "[email protected]"}]list<user> users =NewArraylist<user>();          Users.add (user); String jsonlist=mapper.writevalueasstring (users);      System.out.println (jsonlist); }  }  

third, JSON string to Java class [JSON deserialization]

Importjava.io.IOException; Importjava.text.ParseException; ImportCom.fasterxml.jackson.databind.ObjectMapper;  Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, IOException {String json= "{\" name\ ": \" Wang \ ", \" age\ ": 20,\" birthday\ ": 844099200000,\" email\ ": \" [Email protected]\ "}"; /*** Objectmapper supports JSON deserialization of data from byte[], File, InputStream, String, and so on. */Objectmapper Mapper=NewObjectmapper (); User User= Mapper.readvalue (JSON, User.class);      SYSTEM.OUT.PRINTLN (user); }  }  

Iv. JSON annotations

Jackson provides a series of annotations to facilitate the control of JSON serialization and deserialization, and some common annotations are described below.

@JsonIgnore This annotation is used on attributes, which is ignored when the JSON operation is performed.

@JsonFormat This annotation is used on attributes to convert the date type directly to the desired format, such as @jsonformat (pattern = "Yyyy-mm-dd hh-mm-ss").

@JsonProperty This annotation is used on attributes to serialize the name of the property to another name, such as serializing the Truename property to name, @JsonProperty ("name").

Importjava.util.Date; Importcom.fasterxml.jackson.annotation.*;  Public classUser {PrivateString name; //no JSON serialization age attribute@JsonIgnorePrivateInteger age; //Formatting Date Properties@JsonFormat (pattern = "yyyy mm month DD Day")      PrivateDate birthday; //serializing the email attribute to mail@JsonProperty ("Mail")      PrivateString Email;  PublicString GetName () {returnname; }       Public voidsetName (String name) { This. Name =name; }             PublicInteger getage () {returnAge ; }       Public voidsetage (Integer age) { This. Age =Age ; }             PublicDate Getbirthday () {returnbirthday; }       Public voidsetbirthday (Date birthday) { This. Birthday =birthday; }             PublicString Getemail () {returnemail; }       Public voidsetemail (String email) { This. email =email; }  }        Importjava.io.IOException; Importjava.text.ParseException; ImportJava.text.SimpleDateFormat; ImportCom.fasterxml.jackson.databind.ObjectMapper;  Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, ioexception {User User=NewUser (); User.setname (Wang); User.setemail ("[Email protected]"); User.setage (20); SimpleDateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd"); User.setbirthday (Dateformat.parse ("1996-10-01")); Objectmapper Mapper=NewObjectmapper (); String JSON=mapper.writevalueasstring (user);          SYSTEM.OUT.PRINTLN (JSON); //output: {"name": "Wang", "Birthday": "September 30, 1996", "Mail": "[email protected]"}    }  }  

V. to initiate

In addition to string, you can also manipulate byte[] and so on. The approximate method name is consistent with the action string.

Reference:

http://blog.csdn.net/accountwcx/article/details/24585987 (the above content is transferred from this article)

JSON serialization and deserialization with Jackson under Java (GO)

Related Article

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.