Заранее благодарим за помощь.
Я использую Spring boot webflux 3 с Spring doc Open API 2.4
Вот записи моих объектов ответа
public record UserResponse(
Integer id,
String name,
ScoreResponse scoreSummary
){
}
public record ScoreResponse(
Integer avgScore,
List score
){
public record Score(
Integer scoreId,
Integer score
){
}
}
Вот класс обработчика
@Component
@RequiredArgsConstructor
public class UserHandler {
private final UserService userService;
private final UserMapper userMapper;
private final ClientAuthorizer clientAuthorizer;
@Bean
@RouterOperations({
@RouterOperation(
path = "/user/{userId}",
produces = {MediaType.APPLICATION_JSON_VALUE},
method = RequestMethod.GET,
beanClass = UserHandler.class,
beanMethod = "getById",
operation = @Operation(
description = "GET user by id", operationId = "getById", tags = "users",
responses = @ApiResponse(
responseCode = "200",
description = "Successful GET operation",
content = @Content(
schema = @Schema(
implementation = UserResponse.class
)
)
),
parameters = {
@Parameter(in = ParameterIn.PATH,name = "userId")
}
)
)
})
public @NonNull RouterFunction userIdRoutes() {
return RouterFunctions.nest(RequestPredicates.path("/user/{userId}"),
RouterFunctions.route()
.GET("", this::getById)
.build());
}
@NonNull
Mono getById(@NonNull ServerRequest request) {
String userId = request.pathVariable("userId");
return authorize(request.method(), request.requestPath())
.then(userService.getUserWithScore(userId))
.flatMap(result -> ServerResponse.ok().body(Mono.just(result), UserResponse.class))
.doOnEach(serverResponseSignal -> LoggingHelper.addHttpStatusToContext(serverResponseSignal, HttpStatus.OK));
}
....
}
Ожидаемый пример в пользовательском интерфейсе Swagger:
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
{
"scoreId": 1073741824,
"score": 1073741824
}
]
}
}
Но реальный пример:
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
"string"
]
}
}
Кроме того, я вижу ошибку в пользовательском интерфейсе
Errors
Resolver error at responses.200.content.application/json.schema.$ref
Could not resolve reference: JSON Pointer evaluation failed while evaluating token "score" against an ObjectElement
Пожалуйста, помогите мне найти то, чего мне не хватает.
После нескольких дней исследований я нашел это, и это сработало, и я получил ожидаемый результат. Но мне нужно понять, есть ли лучший подход или это нормально.
Добавлено ниже определение компонента в моем классе-обработчике.
@Bean
public OpenApiCustomizer schemaCustomizer() {
ResolvedSchema resolvedSchema = ModelConverters.getInstance()
.resolveAsResolvedSchema(new AnnotatedType(Score.class));
return openApi - > openApi
.schema(resolvedSchema.schema.getName(), resolvedSchema.schema);
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... -rendering
Spring boot 3 open api - поле массива в классе ответа не отображается ⇐ JAVA
Программисты JAVA общаются здесь
1710663403
Гость
Заранее благодарим за помощь.
Я использую Spring boot webflux 3 с Spring doc Open API 2.4
Вот записи моих объектов ответа
public record UserResponse(
Integer id,
String name,
ScoreResponse scoreSummary
){
}
public record ScoreResponse(
Integer avgScore,
List score
){
public record Score(
Integer scoreId,
Integer score
){
}
}
Вот класс обработчика
@Component
@RequiredArgsConstructor
public class UserHandler {
private final UserService userService;
private final UserMapper userMapper;
private final ClientAuthorizer clientAuthorizer;
@Bean
@RouterOperations({
@RouterOperation(
path = "/user/{userId}",
produces = {MediaType.APPLICATION_JSON_VALUE},
method = RequestMethod.GET,
beanClass = UserHandler.class,
beanMethod = "getById",
operation = @Operation(
description = "GET user by id", operationId = "getById", tags = "users",
responses = @ApiResponse(
responseCode = "200",
description = "Successful GET operation",
content = @Content(
schema = @Schema(
implementation = UserResponse.class
)
)
),
parameters = {
@Parameter(in = ParameterIn.PATH,name = "userId")
}
)
)
})
public @NonNull RouterFunction userIdRoutes() {
return RouterFunctions.nest(RequestPredicates.path("/user/{userId}"),
RouterFunctions.route()
.GET("", this::getById)
.build());
}
@NonNull
Mono getById(@NonNull ServerRequest request) {
String userId = request.pathVariable("userId");
return authorize(request.method(), request.requestPath())
.then(userService.getUserWithScore(userId))
.flatMap(result -> ServerResponse.ok().body(Mono.just(result), UserResponse.class))
.doOnEach(serverResponseSignal -> LoggingHelper.addHttpStatusToContext(serverResponseSignal, HttpStatus.OK));
}
....
}
Ожидаемый пример в пользовательском интерфейсе Swagger:
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
{
"scoreId": 1073741824,
"score": 1073741824
}
]
}
}
Но реальный пример:
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
"string"
]
}
}
Кроме того, я вижу ошибку в пользовательском интерфейсе
Errors
Resolver error at responses.200.content.application/json.schema.$ref
Could not resolve reference: JSON Pointer evaluation failed while evaluating token "score" against an ObjectElement
Пожалуйста, помогите мне найти то, чего мне не хватает.
После нескольких дней исследований я нашел это, и это сработало, и я получил ожидаемый результат. Но мне нужно понять, есть ли лучший подход или это нормально.
Добавлено ниже определение компонента в моем классе-обработчике.
@Bean
public OpenApiCustomizer schemaCustomizer() {
ResolvedSchema resolvedSchema = ModelConverters.getInstance()
.resolveAsResolvedSchema(new AnnotatedType(Score.class));
return openApi - > openApi
.schema(resolvedSchema.schema.getName(), resolvedSchema.schema);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78174388/spring-boot-3-open-api-field-of-array-in-response-class-is-not-rendering[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия