码迷,mamicode.com
首页 > Web开发 > 详细

com.fasterxml.jackson包序列化json对象和反序列化

时间:2020-07-19 16:07:17      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:jpa   toc   ssi   fail   mapper   code   factor   set   error   

需要序列化的类需实现接口:

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对象和反序列化

标签:jpa   toc   ssi   fail   mapper   code   factor   set   error   

原文地址:https://www.cnblogs.com/zhuwenjoyce/p/13339191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!