1. 程式人生 > >Jackson 列舉序列化/反序列化

Jackson 列舉序列化/反序列化

列舉類:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Created by Administrator on 2017/1/9.
 */
public enum TestEnum {

    A(1,"1"),
    B(2,"2");

    private int code;
    private String description;

    private TestEnum(int code, String description){
        this.code = code;
        this.description = description;
    }

    @JsonCreator
    public static TestEnum getItem(int code){
        for(TestEnum item : values()){
            if(item.getCode() == code){
                return item;
            }
        }
        return null;
    }

    @JsonValue
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
例項類:
public static class TestEnums{
        int code =1;
        TestEnum testEnum = TestEnum.B;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public TestEnum getTestEnum() {
            return testEnum;
        }

        public void setTestEnum(TestEnum testEnum) {
            this.testEnum = testEnum;
        }
    }

方案:

利用 @JsonCreator 與  @JsonValue 註解:

JsonCreator :反序列化時的 初始化函式,入參為 對應該列舉的 json值

JsonVale:序列化時 列舉對應生成的值

測試類:

@org.junit.Test
    public void enumJsonTest(){
        TestEnums testEnums = new TestEnums();
        String json = JsonUtil.toJson(testEnums);

        System.out.println(json);

        TestEnums target = JsonUtil.toObject(json,TestEnums.class);
        System.out.println("");
    }

輸出:

{"code":1,"testEnum":2}