Using Jackson for JSON parsing and serialization under Java

Source: Internet
Author: User
Tags dateformat

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. Here are some examples of how Jackson's JSON operations work.

First, the preparatory work

Jackson has 1.x series and 2.x series, 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

A maven dependency is enough.

<Dependency>    <groupId>Com.fasterxml.jackson.core</groupId>    <Artifactid>Jackson-databind</Artifactid>    <version>2.5.3</version></Dependency>

Importjava.util.Date;/*** JSON serialization and deserialization using the user class*/ 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; } @Override PublicString toString () {return"user{" + "name=" + name + ' \ ' + ", age=" + Age + ", birthday=" + Birthday + ", email= '" + email + ' \ ' + '} '; }}

Second, Java object to Json[json serialization]

Importjava.io.IOException;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.ArrayList;Importjava.util.List;ImportCom.fasterxml.jackson.databind.ObjectMapper; Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, ioexception {User User=NewUser (); User.setname ("Zhangsan"); 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": "Zhangsan", "Age": "Birthday": 844099200000, "email": "[email protected]"}String JSON =mapper.writevalueasstring (user);        SYSTEM.OUT.PRINTLN (JSON); //Java Collection goto JSON//output: [{"Name": "Zhangsan", "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 to Java class [JSON deserialization]

 Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, IOException {String json= "{\" name\ ": \" zhangsan\ ", \" 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); }}

Results

User{name= ' Zhangsan ', age=20, Birthday=tue Oct, 00:00:00 CST 1996, email= ' [email protected] '}
 Public classJacksondemo { Public StaticObjectmapper mapper =NewObjectmapper ();  Public Static voidMain (string[] args)throwsParseException, IOException {String json= "[{\" name\ ": \" zhangsan\ ", \" age\ ": 20,\" birthday\ ": 844099200000,\" email\ ": \" [Email protected]\ "}]"; List<User> beanlist = Mapper.readvalue (JSON,NewTypereference<list<user>>() {});    System.out.println (beanlist); }}

Results

[User{name= ' Zhangsan ', age=20, Birthday=tue Oct, 00:00:00 CST 1996, email= ' [email protected] '}]

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").

ImportCom.fasterxml.jackson.annotation.JsonFormat;ImportCom.fasterxml.jackson.annotation.JsonIgnore;ImportCom.fasterxml.jackson.annotation.JsonProperty;Importjava.util.Date;/*** JSON serialization and deserialization using the user class*/ 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 ("My_email")    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; } @Override PublicString toString () {return"user{" + "name=" + name + ' \ ' + ", age=" + Age + ", birthday=" + Birthday + ", email= '" + email + ' \ ' + '} '; }}
ImportCom.fasterxml.jackson.databind.ObjectMapper;Importjava.io.IOException;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat; Public classJacksondemo { Public Static voidMain (string[] args)throwsParseException, ioexception {User User=NewUser (); User.setname ("Zhangsan"); 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); }}
{"Name": "Zhangsan", "Birthday": "September 30, 1996", "My_email": "[email protected]"}

Using Jackson for JSON parsing and serialization under Java

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.