【发布时间】:2021-10-09 13:53:29
【问题描述】:
我有一个返回项目数组的 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结构错误,测试列表也不应该存在。
【问题讨论】:
标签: json spring-boot jackson spring-webflux