jackson常用代码示例

Published on 2021-09-17 17:48 in 分类: 随笔 with 狂盗一枝梅
分类: 随笔

1.序列化

ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(object);

2.反序列化

ObjectMapper objectMapper = new ObjectMapper();
String str = "";
T t = objectMapper.readValue(str,T.class);

3.对日期的支持

默认不支持对LocalDateTime类型的序列化和反序列化,需要做特殊配置

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.util.StringUtils;

public class ObjectMapperFactory {
    public ObjectMapperFactory() {
    }

    public static ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addSerializer(LocalDateTime.class, new ObjectMapperFactory.LocalDateTimeSerializer());
        timeModule.addDeserializer(LocalDateTime.class, new ObjectMapperFactory.LocalDateTimeDeserializer());
        objectMapper.registerModule(timeModule);
        return objectMapper;
    }

    static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        LocalDateTimeDeserializer() {
        }

        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            String timestamp = jsonParser.getValueAsString();
            return LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
    }

    static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        LocalDateTimeSerializer() {
        }

        public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (!StringUtils.isEmpty(localDateTime)) {
                jsonGenerator.writeString(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        }
    }
}

4.对复杂类型反序列化的支持

Result<List<T>> result=ObjectMapperFactory
                    .getObjectMapper()
                    .readValue(string, new TypeReference<Result<List<T>>>() {
                    });

5.自定义字段映射

在对应字段使用JsonProperty注解

@JsonProperty("create_date")
private LocalDateTime createDate;

6.忽略不识别的字段

在实体类上加上以下字段

@JsonIgnoreProperties(ignoreUnknown = true)

7.驼峰转下划线

方法一:通过ObjectMapper设置(不推荐)

mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

方法二:通过在application.properties增加如下配置

spring.jackson.property-naming-strategy=CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

这种方法可能会对swagger的使用产生影响

方法三:采用在实体增加注解实现

//实现驼峰转下划线
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class BaseResultVO {
}

实体继承该类即可。如此不用每个类的字段都注明@jsonproperty注解

方法四:使用JsonProperty注解挨个添加

@JsonProperty("create_date")
private LocalDateTime createDate;

#jackson #序列化 #反序列化
目录
复制 复制成功