json - 如何让 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 结构错误,测试列表也不应该存在。
解决方案
我认为您需要Bean
像这样配置。
@Configuration
public class ApplicaitonConfiguration {
@Bean
ObjectMapper objectMapper() {
var mapper = JsonMapper.builder().addModules(new JavaTimeModule()).build();
// Enable your features...
return mapper;
}
}
推荐阅读
- java - 为什么列表大小返回 0?
- python - 如何分组两列和单词计算熊猫(或python)中的最后一列
- mysql - 如何在 macOS Mojave 上打开 MYSQL 端口 8889 / 3306?
- r - 按组用中位数替换 NA 值
- reinforcement-learning - 如何在openai健身房环境中修改代理?
- python - Python中的逆分数
- python - 从 PyTorch DataLoader 获取单个随机示例
- image-processing - 计算颜色时刻
- python-3.x - 如何使用 scrapy 获取 xlink:href/svg id 的名称?
- android - 将个人资料图片添加到底部 AppBarLayout(Android)