白季飞龙的个人主页

Jackson大杂烩

Jackson解析泛型数据

Java示例代码

package bj;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class Foo {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        Object o = objectMapper.readValue("[1,2,3]\n", objectMapper.getTypeFactory().constructParametricType(
                List.class, Integer.class
        ));
        System.out.println(o);
    }
}

控制台输出

[1, 2, 3]

注意: Jackson解析字符串要用方法com.fasterxml.jackson.databind.ObjectMapper#readValue(java.lang.String, com.fasterxml.jackson.databind.JavaType),而不是com.fasterxml.jackson.databind.ObjectMapper#convertValue(java.lang.Object, java.lang.Class<T>)

在SpringBoot项目中配置全局Jackson

自定义一个org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer的bean即可。

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return jacksonObjectMapperBuilder ->
            jacksonObjectMapperBuilder.featuresToDisable(
                    SerializationFeature.FAIL_ON_EMPTY_BEANS);
}

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道