Json解析工具Jackson(使用注解)

===================================

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Date;

/**
 * Created by leo on 2016/7/28.
 */
@JsonIgnoreProperties(value = { "word" })
public class Person {
    private String name;
    private int age;
    private boolean sex;
    private Date birthday;
    private String word;
    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;
    }



    // 反序列化一个固定格式的Date
    @JsonDeserialize(using = CustomDateDeserialize.class)
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getWord() {
        return word;
    }

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

    // 序列化指定格式的double格式
    @JsonSerialize(using = CustomDoubleSerialize.class)
    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 + "]";
    }

}




===================================

 

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by leo on 2016/7/28.
 */
public class Demo {
    public static void main(String[] args) {

//        writeJsonObject();

        readJsonObject();
    }

    // 直接写入一个对象(所谓序列化)
    public static void writeJsonObject() {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person("nomouse", 25, true, new Date(), "程序员",
                2500.0);
        try {
            mapper.writeValue(new File("c:/person.json"), person);
            mapper.writeValue(new File("c:/person.json"), person);
            mapper.writeValue(new File("c:/person.json"), person);
        } 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 {
            Person person = mapper.readValue(new File("c:/person1.json"),
                    Person.class);
            System.out.println(person.toString());
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}






===================================

 

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.DecimalFormat;

/**
 * Created by leo on 2016/7/28.
 */
public class CustomDoubleSerialize  extends JsonSerializer<Double> {
    private DecimalFormat df = new DecimalFormat("##.00");

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

        jgen.writeString(df.format(value));
    }
}




===================================

 

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by leo on 2016/7/28.
 */
public class CustomDateDeserialize extends JsonDeserializer<Date> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        Date date = null;
        try {
            System.out.println(jp.getText());
            date = sdf.parse(jp.getText());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}




===================================

 

首先去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload。Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.2.3,2.x系列有3个jar包需要下载:

jackson-core-2.2.3.jar(核心jar包, 下载地址

jackson-annotations-2.2.3.jar(该包提供Json注解支持, 下载地址

jackson-databind-2.2.3.jar( 下载地址

===================================

 

写入的文件:{"name":"nomouse","age":25,"sex":true,"birthday":1469688430875,"salary":"2500.00"}


读出的文件:{"name":"nomouse","age":25,"sex":true,"birthday":"2016-01-01","salary":"2500.00","word":"逍遥圣婴"}


2016-01-01
Person [name=nomouse, age=25, sex=true, birthday=Fri Jan 01 00:00:00 CST 2016, word=null, salary=2500.0]

==================================================


  • @JsonIgnoreProperties

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

  • @JsonIgnore

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

  • @JsonFormat

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

  • @JsonSerialize

        此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

  1. public class CustomDoubleSerialize extends JsonSerializer<Double> {  
  2.   
  3.     private DecimalFormat df = new DecimalFormat("##.00");  
  4.   
  5.     @Override  
  6.     public void serialize(Double value, JsonGenerator jgen,  
  7.             SerializerProvider provider) throws IOException,  
  8.             JsonProcessingException {  
  9.   
  10.         jgen.writeString(df.format(value));  
  11.     }  
  12. }  
  • @JsonDeserialize

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

  1. public class CustomDateDeserialize extends JsonDeserializer<Date> {  
  2.   
  3.     private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  4.   
  5.     @Override  
  6.     public Date deserialize(JsonParser jp, DeserializationContext ctxt)  
  7.             throws IOException, JsonProcessingException {  
  8.   
  9.         Date date = null;  
  10.         try {  
  11.             date = sdf.parse(jp.getText());  
  12.         } catch (ParseException e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.         return date;  
  16.     }  





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值