springfox.documentation.spring.web.json.Json Java Examples

The following examples show how to use springfox.documentation.spring.web.json.Json. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringfoxJsonSerializer.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
    public Json toJson(Object toSerialize) {
        if (!(toSerialize instanceof Swagger)) {
            return super.toJson(toSerialize);
        }
        Swagger swagger = (Swagger)toSerialize;

        swagger.getPaths().forEach((key, path) ->{
            Operation get = path.getGet();
            if (get != null) {

                List<Parameter> parameters = get.getParameters();
                if (parameters != null) {
                    parameters.removeIf(parameter -> parameter.getName().startsWith("records[0]."));
                }
            }
        });

        return super.toJson(swagger);
//        return super.toJson(toSerialize);
    }
 
Example #2
Source File: RoadSwagger2Controller.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@GetMapping("/{group}/{version}/swagger")
public ResponseEntity<Json> getDocumentation(@PathVariable String group, @PathVariable String version) {
  return Optional
      .of(group)
      .map(documentationCache::documentationByGroup)
      .map(mapper::mapDocumentation)
      .map(jsonSerializer::toJson)
      .map(json -> new ResponseEntity<Json>(json, HttpStatus.OK))
      .orElse(new ResponseEntity<Json>(HttpStatus.BAD_REQUEST));
}
 
Example #3
Source File: Knife4jController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = DEFAULT_SORT_URL,
        method = RequestMethod.GET,
        produces = {APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE})
@ResponseBody
public ResponseEntity<Json> apiSorts(@RequestParam(value = "group",required = false) String swaggerGroup, HttpServletRequest request) {
    String groupName = Optional.ofNullable(swaggerGroup).orElse("default");
    Documentation documentation = this.documentationCache.documentationByGroup(groupName);
    if (documentation == null) {
        LOGGER.warn("Unable to find specification for group {},use default", groupName);
        documentation = this.documentationCache.documentationByGroup("default");
        if (documentation == null) {
            LOGGER.warn("Unable to find specification for group default");
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    Swagger swagger = this.mapper.mapDocumentation(documentation);
    UriComponents uriComponents = null;

    try {
        uriComponents = HostNameProvider.componentsFrom(request, swagger.getBasePath());
    } catch (Throwable var9) {
        LOGGER.error(var9.getClass().getName() + ":" + var9.getMessage());
        if (var9 instanceof NoClassDefFoundError) {
            String msg = var9.getMessage();
            if (msg != null && !"".equals(msg) && msg.endsWith("HostNameProvider")) {
                uriComponents = SwaggerBootstrapUiHostNameProvider.componentsFrom(request, swagger.getBasePath());
            }
        }
    }

    swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
    if (Strings.isNullOrEmpty(swagger.getHost())) {
        swagger.host(this.hostName(uriComponents));
    }
    extend(swagger);
    SwaggerExt swaggerExt = new SwaggerExt(swagger);
    swaggerExt.setSwaggerBootstrapUi(this.initSwaggerBootstrapUi(request, documentation, swaggerExt));
    return new ResponseEntity<>(this.jsonSerializer.toJson(swaggerExt), HttpStatus.OK);
}
 
Example #4
Source File: SwaggerConfig.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@RequestMapping(value = "/v2/api-docs", method = RequestMethod.GET, produces = { "application/json",
		"application/hal+json" })
@ResponseBody
public ResponseEntity<Json> getDocumentation(
		@RequestParam(value = "group", required = false) String swaggerGroup,
		HttpServletRequest servletRequest) {
	return swagger2Controller.getDocumentation(swaggerGroup, servletRequest);
}
 
Example #5
Source File: FastJsonHttpMessageConverterTest.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwagger() throws HttpMessageNotWritableException, IOException{
    Json value = new Json("{\"swagger\":\"2.0\"");
    HttpOutputMessage outMessage = new MockHttpOutputMessage(){
        
        @Override
        public HttpHeaders getHeaders() {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            return httpHeaders;
        }
    };
    new FastJsonHttpMessageConverter().write(value, null, outMessage);
    Assert.assertTrue((outMessage.getBody().toString().startsWith("{\"swagger\":\"2.0\"")));
}
 
Example #6
Source File: SwaggerJsonSerializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void write(JSONSerializer serializer, //
                  Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.getWriter();
    Json json = (Json) object;
    String value = json.value();
    out.write(value);
}
 
Example #7
Source File: WebConfig.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Gson gson() {
    final GsonBuilder builder = new GsonBuilder();
    // support swagger json
    builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());

    return Converters.registerDateTime(builder).create();
}
 
Example #8
Source File: PresentationConfiguration.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public static Gson gson() {
    GsonBuilder gsonBuilder = new GsonBuilder()
            .disableHtmlEscaping()
            .registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())
            .registerTypeAdapter(PlatformIO.class, new PlatformIO.Serializer()) // Exclusion de hasPasswords lorsqu'il est null
            .registerTypeAdapter(PropertyOutput.class, new PropertyOutput.Serializer()) // Exclusion et récursivité
            .registerTypeAdapter(AbstractValuedPropertyIO.class, new AbstractValuedPropertyIO.Adapter()) // Classe abstraite
            .registerTypeAdapter(AbstractDifferingPropertyOutput.class, new AbstractDifferingPropertyOutput.Adapter()) // Classe abstraite
            .registerTypeAdapter(PlatformChangeOutput.class, new PlatformChangeOutput.Adapter()) // Classe abstraite
            .serializeNulls()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes field) {
                    // Ceci est nécessaire pour éviter des erreurs 500 lorsqu'on requête /rest/manage/beans:
                    // "Could not write JSON" "Attempted to serialize java.lang.Class" "Forgot to register a type adapter?"
                    // à cause de org.springframework.boot.actuate.beans.BeansEndpoint.BeanDescriptor
                    // Plus de doc sur le sujet: https://www.baeldung.com/gson-exclude-fields-serialization
                    return field.getDeclaredType().getTypeName().equals("java.lang.Class<?>");
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            // On doit exclure ces classes de la désérialization pour éviter une boucle circulaire infinie
            // lorsqu'on requête /rest/manage/mappings (cf. #414)
            // et dans ce cas une ExclusionStrategy ne fonctionne pas (bug connu de Gson) :
            .registerTypeAdapter(StandardWrapper.class, (JsonSerializer<StandardWrapper>) (src, typeOfSrc, context) -> null);
    try {
        // idem, mais comme cette classe est package-private, impossible de l'importer directement :
        gsonBuilder.registerTypeAdapter(Class.forName("org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext"), (JsonSerializer) (src, typeOfSrc, context) -> null);
    } catch (ClassNotFoundException ignored) {
    }
    return gsonBuilder.create();
}
 
Example #9
Source File: SpringfoxJsonToGsonAdapter.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
    final JsonParser parser = new JsonParser();
    return parser.parse(json.value());
}
 
Example #10
Source File: SpringfoxJsonToGsonAdapter.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
    final JsonParser parser = new JsonParser();
    return parser.parse(json.value());
}