码迷,mamicode.com
首页 > 其他好文 > 详细

Jackson(使用注解)

时间:2017-05-18 01:10:20      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:des   sse   serial   override   proc   err   介绍   jackson   private   

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();
        }
    }
}
技术分享

Jackson(使用注解)

标签:des   sse   serial   override   proc   err   介绍   jackson   private   

原文地址:http://www.cnblogs.com/ilinuxer/p/6869998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!