com.fasterxml.jackson包序列化json对象和反序列化
Posted 梦幻朵颜 Joyce Zhu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了com.fasterxml.jackson包序列化json对象和反序列化相关的知识,希望对你有一定的参考价值。
需要序列化的类需实现接口:
public class ResponseModel implements Serializable {
序列化和反序列化代码例子:
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.joyce.jpa.model.ResponseModel; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class JsonTest { static Logger logger = LoggerFactory.getLogger(JsonTest.class); @Test public void test1() throws JsonProcessingException { ResponseModel model = new ResponseModel(); model.setCode("9999").setError("未知错误"); String jsonStr = buildJsonStrBy(model); logger.info("jsonStr == " + jsonStr); } String buildJsonStrBy(ResponseModel model) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); return mapper.writeValueAsString(model); } ResponseModel deserializingToCouponUserBy(String jsonStr) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL , false); // mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT , false); // mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT , false); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES , false); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES , false); return mapper.readValue(jsonStr, ResponseModel.class); } }
end.
以上是关于com.fasterxml.jackson包序列化json对象和反序列化的主要内容,如果未能解决你的问题,请参考以下文章
RabbitMQ反序列化失败 com.fasterxml.jackson.databind.exc.MismatchedInputException
com.fasterxml.jackson.databind.JsonMappingException 没有从字符串值('1')反序列化的字符串参数构造函数/工厂方法
尝试反序列化子类时“com.fasterxml.jackson.databind.exc.InvalidTypeIdException:无法解析类型 ID”
fasterxml jackson 的包冲突太垃圾太恶心了: Could not initialize class com.fasterxml.jackson.databind.Seriali...
com.fasterxml.jackson.databind.exc.MismatchedInputException:无法反序列化对象实例出 START_ARRAY 令牌
使用 com.fasterxml.jackson.databind.ObjectMapper 在序列化/反序列化 JSON 内容期间从异常日志中删除敏感数据