jackson進行json序列化和反序列化

luoyu_5812發表於2016-06-17
package com.csair.soc.aircrew.rostereditor.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;


public abstract class JacksonUtil {
    public static final ObjectMapper OM = new ObjectMapper();
    static{
    OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    public static <T> T getData(byte[] o) {
        T data = null;
        try {
            data = OM.readValue((byte[]) o, new TypeReference<T>(){});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    
    public static <T> T getData(byte[] o,TypeReference<T> typeReference) {
    T data = null;
        try {
            data = OM.readValue((byte[]) o, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    public static byte[] toBytes(Object mb) {
        byte[] bytes = null;
        try {
            bytes = OM.writeValueAsBytes(mb);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return bytes;
    }
    public static String toString(Object mb) {
        String bytes = null;
        try {
            bytes = OM.writeValueAsString(mb);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return bytes;
    }
    public static <T> T getData(String jsonStr,TypeReference<T> typeReference) {
        T data = null;
        try {
            data = OM.readValue(jsonStr, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

}


jackson的pom依賴配置如下

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.4</version>
</dependency>


user是個實體,進行json序列化

String str = JacksonUtil.toString(user);
System.out.println(str);

從json字串反序列化獲取實體

user = JacksonUtil.getData(str, new TypeReference<User>() {
});


相關文章