Location>code7788 >text

springboot: call the interface to return data garbled solution

Popularity:124 ℃/2024-10-29 16:22:04

After pulling down the project from git and running the service, it starts fine, but the service interface is garbled when using swagger and postman.

The data returned by each interface is garbled, but the logs printed on the console are normal, and subsequently found that the return type of the data is not the common application/json, but application/x-jackson-smile, so the problem should be solved by changing the data type

The controller class is annotated with RestController, but the contentType is still not json.

By declaring the contentType at the interface, you can solve the problem of interfaces returning garbled code, but it's too cumbersome to declare them one by one.

Baidu finally got the solution after a long time
Implement springboot's web configuration class by adding global configuration for the default contentType
According to the following, all interfaces can optionally pass a parameter mediaType, if the value is xml, then return data in xml format; if the value is json, then return data in json format when not passed, the default return data in json format

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        (true)
                .defaultContentType(MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML)
                .parameterName("mediaType")

                .mediaType("json",MediaType.APPLICATION_JSON)
                .mediaType("xml",MediaType.APPLICATION_XML);


    }
}