springfox(swagger2) does not work with GsonHttpMessageConverterConfig

前端 未结 5 1899
耶瑟儿~
耶瑟儿~ 2020-12-08 17:42

What I am trying to build is a spring-boot (v1.2.3) application and expose my Rest API with SpringFox(swagger2) v2.0.0

my Swagger Spring config



        
5条回答
  •  渐次进展
    2020-12-08 18:04

    Ran into a similar problem but found a little different solution which is also using the above mentioned serializer.

    We define a Bean to be able to autowire Gson objects. For fixing the issue with Swagger the important part there is to also add "registerTypeAdapter" for the Json class.

    @Configuration
    public class GsonConfiguration {
       @Bean
       public Gson gson() {
          return new GsonBuilder().registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter()).create();
       }
    }
    

    The content of SpringfoxJsonToGsonAdapter is the same as above and only listed here for completeness.

    public class SpringfoxJsonToGsonAdapter implements JsonSerializer {
        @Override
        public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
            final JsonParser parser = new JsonParser();
            return parser.parse(json.value());
        }
    }
    

    For using the Gson object just do something like this:

    @Component
    public class Foobar {
       @Autowired
       Gson gson;
    
       @Autowired
       public Foobar() {
          // ... some constructor work ...
       }
    
       public void someMethod() {
          System.out.println(gson.toJson(...)); // Fill in some object ;-)
       }
    }
    

提交回复
热议问题