首页 > 解决方案 > 如何让 webflux 端点用每个项目的对象名称序列化 json

问题描述

我有一个返回项目数组的 webflux 端点。我试图让它将对象名称添加到@JsonRootName 指定的数组中的每个项目中。我试过像这样使用 Jackson2ObjectMaper 配置对象映射器。我正在使用 SpringBoot 2.4.4。

@Configuration
@EnableWebFlux
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            builder.modules(new JavaTimeModule());
            builder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE);
            builder.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            builder.indentOutput(true);
        };
    }
}

我的端点如下所示:

@GetMapping(value = "/all/{id}", produces = "application/json")
public ResponseEntity<Flux<EventsMetaData>> getAllEventsByUser(@PathVariable String id) {
    return ResponseEntity.ok(eventsMetaDataService.getAllEventsByUserId(id));
}

Json 响应是:

[
    {
        "id": "342424234",
        "userid": "34324242",
        "eventId": null,
        "eventName": "Test 1",
        "eventDetails": null
    },
    {
        "id": "43435235",
        "userid": "34244242",
        "eventId": null,
        "eventName": "Test",
        "eventDetails": null
    }
]

预期输出:

[
   Event: {
        "id": "342424234",
        "userid": "34324242",
        "eventId": null,
        "eventName": "Test 1",
        "eventDetails": null
    },
    Event: {
        "id": "43435235",
        "userid": "34244242",
        "eventId": null,
        "eventName": "Test",
        "eventDetails": null
    }
]

但是,当我的对象使用 @JsonRootName 注释时,我没有得到根对象

@JsonRootName(value = "Event")
public class Event {

欢迎提出任何建议。

编辑:从配置中删除@EnableWebFlux 后,它给了我一个根包装值,但仍然不像它应该使用列表那样:

{
    "List": [
        {
            "id": "610bd71077cfcd2ee941217c",
            "eventName": "Test",
            "eventDetails": null,
            "eventDateTime": null,
            "eventLink": null
        }
    ]
}

然而,单个对象尊重包装器,如下所示:

{
    "event": {
        "id": "610bd71077cfcd2ee941217c",
        "eventName": "Test",
        "eventDetails": null,
        "eventDateTime": null,
        "eventLink": null
    }
}

链接到复制项目https://gitlab.com/dmbeer/so-68651608即使 json 结构错误,测试列表也不应该存在。

标签: jsonspring-bootjacksonspring-webflux

解决方案


我认为您需要Bean像这样配置。

@Configuration
public class ApplicaitonConfiguration {

    @Bean
    ObjectMapper objectMapper() {

        var mapper = JsonMapper.builder().addModules(new JavaTimeModule()).build();

        // Enable your features...

        return mapper;
    }
}

推荐阅读