1. 程式人生 > >Json解析工具Jackson(使用註解)

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

接上一篇文章Json解析工具Jackson(簡單應用),jackson在實際應用中給我們提供了一系列註解,提高了開發的靈活性,下面介紹一下最常用的一些註解

  • @JsonIgnoreProperties

         此註解是類註解,作用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。

  • @JsonIgnore

         此註解用於屬性或者方法上(最好是屬性上),作用和上面的@JsonIgnoreProperties一樣。

  • @JsonFormat

        此註解用於屬性或者方法上(最好是屬性上),可以方便的把Date型別直接轉化為我們想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

  • @JsonSerialize

        此註解用於屬性或者getter方法上,用於在序列化時嵌入我們自定義的程式碼,比如序列化一個double時在其後面限制兩位小數點。

package com.xiaowu.jackson.anno;

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

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

/**
 * 
 * @author xiaowu
 *
 */
public class CustomDoubleSerialize extends JsonSerializer<Double>{
	
	private DecimalFormat dec = new DecimalFormat("##.00");

	/**
	 * @param JsonGenerator  json流輸出
	 */
	public void serialize(Double value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		// TODO Auto-generated method stub
		jgen.writeString(dec.format(value));
		
	}

}
  • @JsonDeserialize

         此註解用於屬性或者setter方法上,用於在反序列化時可以嵌入我們自定義的程式碼,類似於上面的@JsonSerialize

package com.xiaowu.jackson.anno;

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

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

/**
 * 
 * @author xiaowu
 *
 */
public class CustomDateDeserialize extends JsonDeserializer<Date>{
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

	public Date deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		// TODO Auto-generated method stub
		Date date = null;
		//String s1 = null;
		try {
			date = sdf.parse(jp.getText());
			//s1 = sdf.format(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

}
完整程式碼:
package com.xiaowu.jackson.anno;

import java.util.Date;

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

/**
 * 
 * @author xiaowu
 *
 */
//表示序列化時忽略的屬性 
@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, 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 + "]";  
    }  

}

package com.xiaowu.jackson.anno;

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

import org.junit.Test;

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

/**
 * 
 * @author xiaowu
 *
 */
public class demo {
	
	 // 直接寫入一個物件(所謂序列化)  
	@Test
    public void writeJsonObject() {  
		
		ObjectMapper mapper = new ObjectMapper();
		Person person = new Person("nomouse", 25, true, new Date(), "程式設計師",  
                2500.0);  
		try {
			mapper.writeValue(new File("d:/person.json"), person);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
	
	// 直接將一個json轉化為物件(所謂反序列化)  
	@Test
    public void readJsonObject() {  
        ObjectMapper mapper = new ObjectMapper();  
  
        try {  
            Person person = mapper.readValue(new File("d:/person.json"),  
                    Person.class);  
            System.out.println(person.toString());  
        } catch (JsonParseException e) {  
            e.printStackTrace();  
        } catch (JsonMappingException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

}