Java下利用Jackson進行JSON解析和序列化

來源:互聯網
上載者:User

標籤:ide   qtp   except   mave   XML   kms   nbd   image   cti   

ava下常見的Json類庫有Gson、JSON-lib和Jackson等,Jackson相對來說比較高效,在項目中主要使用Jackson進行JSON和Java對象轉換,下面給出一些Jackson的JSON操作方法。

一、準備工作

Jackson有1.x系列和2.x系列,2.x系列有3個jar包需要下載:
jackson-core-2.2.3.jar(核心jar包)
jackson-annotations-2.2.3.jar(該包提供Json註解支援)
jackson-databind-2.2.3.jar

一個maven依賴就夠了

<dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.5.3</version></dependency>

import java.util.Date;/** * JSON序列化和還原序列化使用的User類 */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 + ‘\‘‘ +                ‘}‘;    }}

二、JAVA對象轉JSON[JSON序列化]

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是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實現。         * ObjectMapper有多個JSON序列化的方法,可以把JSON字串儲存File、OutputStream等不同的介質中。         * writeValue(File arg0, Object arg1)把arg1轉成json序列,並儲存到arg0檔案中。         * writeValue(OutputStream arg0, Object arg1)把arg1轉成json序列,並儲存到arg0輸出資料流中。         * writeValueAsBytes(Object arg0)把arg0轉成json序列,並把結果輸出成位元組數組。         * writeValueAsString(Object arg0)把arg0轉成json序列,並把結果輸出成字串。         */        ObjectMapper mapper = new ObjectMapper();        //User類轉JSON        //輸出結果:{"name":"zhangsan","age":20,"birthday":844099200000,"email":"[email protected]"}        String json = mapper.writeValueAsString(user);        System.out.println(json);        //Java集合轉JSON        //輸出結果:[{"name":"zhangsan","age":20,"birthday":844099200000,"email":"[email protected]"}]        List<User> users = new ArrayList<User>();        users.add(user);        String jsonlist = mapper.writeValueAsString(users);        System.out.println(jsonlist);    }}

三、JSON轉Java類[JSON還原序列化]

public class JacksonDemo {    public static void main(String[] args) throws ParseException, IOException {        String json = "{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"[email protected]\"}";        /**         * ObjectMapper支援從byte[]、File、InputStream、字串等資料的JSON還原序列化。         */        ObjectMapper mapper = new ObjectMapper();        User user = mapper.readValue(json, User.class);        System.out.println(user);    }}

結果

User{name=‘zhangsan‘, age=20, birthday=Tue Oct 01 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);    }}

結果

[User{name=‘zhangsan‘, age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email=‘[email protected]‘}]

四、JSON註解

Jackson提供了一系列註解,方便對JSON序列化和還原序列化進行控制,下面介紹一些常用的註解。
@JsonIgnore 此註解用於屬性上,作用是進行JSON操作時忽略該屬性。
@JsonFormat 此註解用於屬性上,作用是把Date類型直接轉化為想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
@JsonProperty 此註解用於屬性上,作用是把該屬性的名稱序列化為另外一個名稱,如把trueName屬性序列化為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序列化和還原序列化使用的User類 */public class User {    private String name;    //不JSON序列化年齡屬性    @JsonIgnore    private Integer age;    //格式化日期屬性    @JsonFormat(pattern = "yyyy年MM月dd日")    private Date birthday;    //序列化email屬性為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(20);        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":"1996年09月30日","my_email":"[email protected]"}

Java下利用Jackson進行JSON解析和序列化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.