Using Jackson for JSON parsing and serialization under Java

Source: Internet
Author: User
Tags dateformat

The common JSON libraries under Ava are Gson, Json-lib, and Jackson, and Jackson is relatively efficient, mainly using Jackson for JSON and Java object transformations in the project, and 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>

Import java.util.date;/** * JSON serialization and deserialization using the user class */public class User {    private String name;    Private Integer age;    Private Date birthday;    private String Email;    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public Integer Getage () {        return age;    }    public void Setage (Integer age) {        this.age = age;    }    Public Date Getbirthday () {        return birthday;    }    public void Setbirthday (Date birthday) {        this.birthday = birthday;    }    Public String Getemail () {        return email;    }    public void Setemail (String email) {        This.email = email;    }    @Override public    String toString () {        return "user{" +                "name= '" + name + ' \ ' +                ", age=" + Age +                " , birthday= "+ Birthday +                ", email= ' + email + ' \ ' + '                } ';}    

Second, Java object to Json[json serialization]

Import Java.io.ioexception;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.list;import Com.fasterxml.jackson.databind.objectmapper;public Class Jacksondemo {public static void main (string[] args) throws ParseException, IOException {User user = new user ()        ;        User.setname ("Zhangsan");        User.setemail ("[email protected]");        User.setage (20);        SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");        User.setbirthday (Dateformat.parse ("1996-10-01"));         /** * Objectmapper is the core of the JSON operation, 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 arg0 into JSON sequence and outputs the result into a wordCharacter string.        */Objectmapper Mapper = new Objectmapper (); User class to JSON//output result: {"name": "Zhangsan", "age": +, "Birthday": 844099200000, "email": "[email protected]"} St        Ring JSON = mapper.writevalueasstring (user);        SYSTEM.OUT.PRINTLN (JSON);        Java collection to JSON//output result: [{"Name": "Zhangsan", "age": +, "Birthday": 844099200000, "email": "[email protected]"}]        list<user> users = new arraylist<user> ();        Users.add (user);        String jsonlist = mapper.writevalueasstring (users);    System.out.println (jsonlist); }}

Third, JSON to Java class [JSON deserialization]

public class Jacksondemo {public    static void Main (string[] args) throws ParseException, 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 = new Objectmapper ();        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 class Jacksondemo {public    static Objectmapper mapper = new Objectmapper ();    public static void Main (string[] args) throws ParseException, IOException {        String json = "[{\" name\ ": \" zhangsan\ ", \" Age\ ": 20,\" birthday\ ": 844099200000,\" email\ ": \" [Email protected]\ "}]";        list<user> beanlist = Mapper.readvalue (JSON, new typereference<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").

Import Com.fasterxml.jackson.annotation.jsonformat;import Com.fasterxml.jackson.annotation.jsonignore;import Com.fasterxml.jackson.annotation.jsonproperty;import java.util.date;/** * JSON serialization and deserialization using the user class */public class user {P    Rivate String name;    No JSON serialization age attribute @JsonIgnore private Integer ages;    Format Date attribute @JsonFormat (pattern = "yyyy mm DD Day") Private date birthday;    The serialized email attribute is mail @JsonProperty ("My_email") private String email;    Public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public Integer Getage () {return age;    public void Setage (Integer age) {this.age = age;    Public Date Getbirthday () {return birthday;    } public void Setbirthday (Date birthday) {this.birthday = birthday;    } public String Getemail () {return email;    } public void Setemail (String email) {this.email = email; } @Override Public String ToString () {return "user{" + "Name= '" + name + ' \ ' + ", age=" + Age +    ", birthday=" + Birthday + ", email= '" + email + ' \ ' + '} '; }}
Import Com.fasterxml.jackson.databind.objectmapper;import Java.io.ioexception;import java.text.ParseException; Import Java.text.simpledateformat;public class Jacksondemo {public    static void Main (string[] args) throws ParseException, IOException {        User user = new User ();        User.setname ("Zhangsan");        User.setemail ("[email protected]");        User.setage (a);        SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");        User.setbirthday (Dateformat.parse ("1996-10-01"));        Objectmapper mapper = new Objectmapper ();        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

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.