Spring boot 3 open api - поле массива в классе ответа не отображаетсяJAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Spring boot 3 open api - поле массива в классе ответа не отображается

Сообщение Гость »

Заранее благодарим за помощь.
Я использую 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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»