jackson解析和序列化json串

Java下常见的Json类库有Gson、JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法。

下载jar包

可以在maven上面下载如下的三个jar包:
jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar
jackson-databind-2.2.3.jar

简单Demo

User类

user类中包含以下基本的类型及集合,其中的注释可以不写直接使用对象序列化:
有如下的三种常用注释
@JsonIgnore 序列化时候忽略这个属性
@JsonProperty 将这个名称换成指定名称
@JsonFormat 格式化日期类型

package cn.xiaoyu.jackson.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonIgnore //不序列化年龄属性
    private int id;
    @JsonProperty("username") //将格式话的后的名称改为username
    private String name;
    private Integer age;
    @JsonFormat(pattern="yyyy-MM-dd") //格式化日期字段 
    private Date birth;
    private List<String> roles = new ArrayList<String>();

    public User(){}
    public User(int id, String name, Integer age, Date birth) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.birth = birth;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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 getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public List<String> getRoles() {
        return roles;
    }
    public void setRoles(List<String> roles) {
        this.roles = roles;
    }
}

Demo类

ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。

writeValue(File file, Object obj)把obj转成json序列,并保存到file文件中。
writeValue(OutputStream output, Object obj)把obj转成json序列,并保存到output输出流中。
writeValueAsBytes(Object obj)把obj转成json序列,并把结果输出成字节数组。
writeValueAsString(Object obj)把obj转成json序列,并把结果输出成字符串。

package cn.xiaoyu.jackson.demo;
import java.util.Date;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.xiaoyu.jackson.domain.User;
public class Demo {
    public static void main(String[] args) throws Exception {
        User user = new User(1,"bubu",23,new Date());
        user.getRoles().add("coder");
        user.getRoles().add("student");

        // 将User对象转换为json字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(user);
        /**
         * {"id":1,"name":"bubu","age":23,"birth":1444330452118,"roles":["coder","student"]}
         * 注意:这儿如果在User.java上面不添加@JsonFormat(pattern = "yyyy-MM-dd")和@JsonIgnore 输出的是上面的类型,否则是:
         * {"id":1,"name":"bubu","birth":"2015-10-08","roles":["coder","student"]}
         */
        System.out.println(jsonStr);

        // 将json串转换为User对象
        User bubu = mapper.readValue(jsonStr, User.class); 
        System.out.println(bubu);
        System.out.println(bubu.getRoles().size());

        //直接读取json的值
        JsonNode root = mapper.readTree(jsonStr);
        JsonNode name = root.path("name");
        JsonNode roles = root.path("roles");
        System.out.println(name.asText());
        System.out.println(roles.size());
        System.out.println(roles.get(0));

    }
}

参考

http://wiki.fasterxml.com/JacksonInFiveMinutes