使用spring boot无法将JSON部分反序列化为Immutables对象

时间:2018-04-14 12:55:44

标签: java spring-boot jackson immutables-library

我有一个JSON文件,我通过restTemplate读取并希望只将某些字段存储到我的对象中。调用是成功的,但我的对象不包含来自JSON的信息。 This是文件,我只对my-channels对象感兴趣。

我的pom.xml:

<!-- SNIP standard stuff generated by start.spring.io -->
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
            <version>2.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.immutables</groupId>
            <artifactId>value</artifactId>
            <version>2.5.6</version>
            <scope>provided</scope>
        </dependency>

我的JacksonConfig禁用了丢失字段的失败并启用了kebab-case:

@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        final ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.registerModule(new Jdk8Module());

        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);

        return objectMapper;
    }
}

保存我的数据的对象。

@Value.Immutable
@JsonSerialize(as = com.example.demo.ImmutableGist.class)
@JsonDeserialize(as = com.example.demo.ImmutableGist.class)
public interface AbstractGist {
    List<ImmutableMyChannels> myChannels();

    @Value.Immutable
    @JsonSerialize(as = ImmutableMyChannels.class)
    @JsonDeserialize(as = ImmutableMyChannels.class)
    interface AbstractMyChannels {
        String channelId();

        String locale();
    }
}

和我使用commandlinerunner的主要内容:

@SpringBootApplication
public class DemoApplication {

    private static final String URL = "https://rawgit.com/Gregsen/936f0dc5f1a83687ada6b64a0fe20a0c/raw/1ee44d3e7aa94851a811108b2606e803f8734c8d/example.json";
    private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @Bean
    public CommandLineRunner run() throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        return args -> {
            ImmutableGist gist = restTemplate.getForObject(URL, ImmutableGist.class);

            log.info(gist.toString());
        };
    }
}

应用程序编译并运行,但输出只是Gist{salesChannels=[]}(减去整个弹簧的默认输出)

1 个答案:

答案 0 :(得分:2)

所以,经过一些更多的摆弄和阅读之后,似乎问题可以解决:

而不是使用@JsonDeserialize(as = ImmutableMyChannels.class),应该使用也会生成的构建器。

@JsonDeserialize(builder = ImmutableMyChannels.Builder.class)