Jackson進行JSON解析和序列化

Java下常見的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]"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章