json - 使用jackson進行序列化/反序列化

Sidyhe發表於2016-06-29
public class JsonHelper {

    static ObjectMapper getMapper() {
        ObjectMapper mapper;

        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    public static String encode(Object object) throws JsonProcessingException {
        return getMapper().writeValueAsString(object);
    }

    public static <T> T decode(String json, Class<T> cls) throws IOException {
        return getMapper().readValue(json, cls);
    }
}

相關文章