Jackson(使用注解)

jackson在实际应用中给我们提供了一系列注解,提高了开发的灵活性,下面介绍一下最常用的一些注解

@JsonIgnoreProperties
此注解是类注解,作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。

@JsonIgnore
此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

@JsonFormat
此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

@JsonSerialize
此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点,将一个Date类型转化成指定类型字符串。

复制代码
public class JsonDoubleSerialize extends JsonSerializer<Double> {

    private DecimalFormat df = new DecimalFormat("##.000");

    @Override
    public void serialize(Double value, JsonGenerator jgen,
                          SerializerProvider provider) throws IOException,
            JsonProcessingException {

        jgen.writeString(df.format(value));
    }
}
复制代码
复制代码
/**
 * 把Date类型序列化成指定合适的字符串
 */
public class JsonDateSerialize extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jgen,
                          SerializerProvider provider)
            throws IOException, JsonProcessingException {
        String formattedDate = "";
        if (date != null) {
            //把日期序列化成yyyy-MM-dd格式的字符串
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            formattedDate = simpleDateFormat.format(date);
        }
        jgen.writeString(formattedDate);
    }
}
复制代码

@JsonDeserialize
此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

复制代码
/**
 * 将一个字符串反序列化成一个Date类型
 */
public class JsonDateDeserialize extends JsonDeserializer<Date> {
    
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        //拿到的是"yyyy-MM-dd"形式的字符串,现在要在json反序列化的时候转化成Date类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = jp.getText();
        if (date == null || date.trim().length() == 0) {
            return null;
        }
        try {
            return format.parse(date);
        } catch (Exception e) {
            
        }
        return null;
    }
}
复制代码

完整例子

复制代码
//表示序列化时忽略的属性
@JsonIgnoreProperties(value = {"word"})
public class Person {
    private String name;
    private int age;
    private boolean sex;
    @JsonSerialize(using = JsonDateSerialize.class)
    @JsonDeserialize(using = JsonDateDeserialize.class)
    private Date birthday;
    private String word;
    @JsonSerialize(using = JsonDoubleSerialize.class)
    private double salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, boolean sex, Date birthday,
                  String word, double salary) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.birthday = birthday;
        this.word = word;
        this.salary = salary;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex
                + ", birthday=" + birthday + ", word=" + word + ", salary="
                + salary + "]";
    }

}
复制代码
复制代码
public class Demo {
    public static void main(String[] args) {

        //writeJsonObject();

        readJsonObject();
    }

    // 直接写入一个对象(所谓序列化)
    public static void writeJsonObject() {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person("zhangsan", 25, true, new Date(), "coder",
                2500.0);
        try {
            String string = mapper.writeValueAsString(person);
            //{"name":"zhangsan","age":25,"sex":true,"birthday":"2016-12-03 22:02:23","salary":"2500.000"}
            System.out.println(string);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 直接将一个json转化为对象(所谓反序列化)
    public static void readJsonObject() {
        ObjectMapper mapper = new ObjectMapper();

        try {
            String string = "{\"name\":\"zhangsan\",\"age\":25,\"sex\":true,\"birthday\":\"2016-12-03 22:02:23\",\"word\":\"coder\",\"salary\":\"2500.000\"}";
            Person person = mapper.readValue(string, Person.class);
            //Person [name=zhangsan, age=25, sex=true, birthday=Sat Dec 03 00:00:00 CST 2016, word=null, salary=2500.0]
            System.out.println(person.toString());
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
复制代码

posted on 2017-05-17 22:55  ilinux_one  阅读(1803)  评论(0编辑  收藏  举报

导航