Search code examples
spring-bootspringdoc

Display Unstructured Object as an Example Response in SpringDoc


I have a class which will represent the **BadRequestResponse **and it will contain every attribute and the reason of validation for it and the number of attribute are not determined for me so I use Map<String,List<String>> for representing each atrribute and failed validation reason

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class BadRequestResponse {

    @Schema(type = "string" , example = "Validation Failed")
    private String message;

    
    private Map<String,List<String>> failed_validation_attributes;
}

and when i call API in case of failed validation it will gives me

{
    "message": "Validation Failed",
    "failed_validation_attributes": {
        "lastName": [
            "Second Name Should Not Be Null or Empty"
        ],
        "firstName": [
            "First Name Should Not Be Null or Empty"
        ]
    }
}

and when i use this class in SpringDoc it gives me Swagger Screenshot

I would like to view example resonse as in swagger doc

{
    "message": "Validation Failed",
    "failed_validation_attributes": {
        "lastName": [
            "Second Name Should Not Be Null or Empty"
        ],
        "firstName": [
            "First Name Should Not Be Null or Empty"
        ]
    }
}

Solution

  • Try below.

        @ArraySchema(arraySchema = @Schema(
                example = "{\"lastName\": [ \"Second Name Should Not Be Null or Empty\" ], \"firstName\": [ \"First Name Should Not Be Null or Empty\"]}"))
        private Map<String, List<String>> failed_validation_attributes;