json處理工具--jackson總結

https://www.cnblogs.com/winner-0715/p/6109225.htmlhtml

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

1、準備工做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數組

注:下載的jar包版本若是太老,可能會出現有些功能不能實現,如:註解不全app

一個maven依賴就夠了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 + '\'' +
                '}';
    }
}
複製代碼

2、JAVA對象轉JSON[JSON序列化]ide

複製代碼
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("zhangsan@163.com");
        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":"zhangsan@163.com"}
        String json = mapper.writeValueAsString(user);
        System.out.println(json);

        //Java集合轉JSON
        //輸出結果:[{"name":"zhangsan","age":20,"birthday":844099200000,"email":"zhangsan@163.com"}]
        List<User> users = new ArrayList<User>();
        users.add(user);
        String jsonlist = mapper.writeValueAsString(users);
        System.out.println(jsonlist);
    }
}
複製代碼

3、JSON轉Java類[JSON反序列化]this

複製代碼
 
 
  import org.codehaus.jackson.JsonParseException;

  import org.codehaus.jackson.map.JsonMappingException;
  import org.codehaus.jackson.map.ObjectMapper;
spa

public class JacksonDemo {
    public static void main(String[] args) throws ParseException, IOException {
        String json = "{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"zhangsan@163.com\"}";
        /**
         * ObjectMapper支持從byte[]、File、InputStream、字符串等數據的JSON反序列化。
         */
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user);
    }
}
複製代碼

結果code

User{name='zhangsan', age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email='zhangsan@163.com'}
複製代碼

  import org.codehaus.jackson.JsonParseException;
  import org.codehaus.jackson.map.JsonMappingException;
  import org.codehaus.jackson.map.ObjectMapper;
  import org.codehaus.jackson.type.TypeReference;



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\":\"zhangsan@163.com\"}]"; 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='zhangsan@163.com'}]

4、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("zhangsan@163.com");
        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":"zhangsan@163.com"}
相關文章
相關標籤/搜索