栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring 解析swagger.json

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring 解析swagger.json

在项目中需要把所有微服务的接口统一管理,swagger上虽然能看到,但是只能分服务,在一个项目中可能就需要找多个服务

在pom中导入


            com.alibaba
            fastjson
            1.2.70
       

直接上源码

public class SwaggerJsonUtil {

    public static String getHost(JSonObject swaggerJson) {
        //JSonObject swaggerJson = JSON.parseObject(swaggerJsonStr,Feature.DisableCircularReferenceDetect);
        return swaggerJson.getString("host");
    }
    
    public static SwaggerInfoVo getInfo(JSonObject swaggerJson) {
        return swaggerJson.getObject("info", SwaggerInfoVo.class);
    }
    
    
    public static List getPathInfo(JSonObject swaggerJson){
        JSonObject paths = swaggerJson.getJSonObject("paths");
        List list = new ArrayList<>();
        //所有的definitions
        Map refMap = getDefinitions(swaggerJson);
        if(paths != null) {
             Iterator> it = paths.entrySet().iterator();
             while(it.hasNext()) {
                 PathInfoVo pathInfo = new PathInfoVo();
                 Entry path = it.next();
                 String pathUrl = path.getKey();
                 pathInfo.setPathUrl(pathUrl);
                 //请求方式
                 JSonObject pathJson = paths.getJSonObject(pathUrl);
                 Set methodSet = pathJson.keySet();
                 //当方法支持多种请求方式时也只取第一种
                 if(CollectionUtils.isNotEmpty(methodSet)) {
                    String httpMethod = methodSet.iterator().next();
                    pathInfo.setHttpMethod(httpMethod);
                    JSonObject methodJson = pathJson.getJSonObject(httpMethod);
                    String summary = methodJson.getString("summary");
                    String operationId = methodJson.getString("operationId");
                    String description = methodJson.getString("description");
                    pathInfo.setDescription(description);
                    pathInfo.setOperationId(operationId);
                    pathInfo.setSummary(summary);
                    JSonArray parameters = methodJson.getJSonArray("parameters");
                    JSonObject responses = methodJson.getJSonObject("responses");
                    List reqParameters = getParameter(parameters,refMap);
                    pathInfo.setReqList(reqParameters);
                    List respList = getResponse(responses,refMap);
                    pathInfo.setRespList(respList);
                 }
                 list.add(pathInfo);
             }
        }
        return list;
    }
    
    
    public static List getResponse(JSonObject responses,Map refMap){
        List respParameters = new ArrayList<>();
        if(responses != null && responses.containsKey("200")) {
            //只解析200的数据
            JSonObject successJson = responses.getJSonObject("200");
            if(successJson.containsKey("schema")) {
                JSonObject schema = successJson.getJSonObject("schema");
                String schemaType = schema.getString("type");
                String ref = "";
                if(schema.containsKey("$ref")) {
                    ref = schema.getString("$ref");
                }
                if("array".equalsIgnoreCase(schemaType)){
                    JSonObject items = schema.getJSonObject("items");
                    if(items.containsKey("$ref")) {
                        ref = schema.getString("$ref");
                    }else {
                        ResponseVo resp = new ResponseVo();
                        resp.setName("");
                        resp.setType(items.getString("type"));
                        respParameters.add(resp);
                    }
                }
                if(StringUtils.isNotBlank(ref)) {
                    String def = ref.substring(14);
                    JSonObject defJson = refMap.get(def);
                //    String type = defJson.getString("type");
                    JSonObject properties = defJson.getJSonObject("properties");
                    Set respKeys = properties.keySet();
                    for(String key : respKeys) {
                        JSonObject respMap = properties.getJSonObject(key);
                        ResponseVo resp = new ResponseVo();
                        resp.setName(key);
                        resp.setFormat(respMap.getString("format"));
                        resp.setDescription(respMap.getString("description"));
                        String respType = respMap.getString("type");
                        resp.setType(StringUtils.isBlank(respType)?"object":respType);
                        resp.setRequired(respMap.getBooleanValue("required"));
                        if(respMap.containsKey("$ref")) {
                            String childRef = respMap.getString("$ref");
                            String childDef = childRef.substring(14);
                            JSonObject childDefJson = refMap.get(childDef);
                            JSonObject childProperties = childDefJson.getJSonObject("properties");
                            getRef(refMap,childProperties,resp,childDef,childDefJson);
                        }else if("array".equalsIgnoreCase(respType)) {
                            JSonObject items = respMap.getJSonObject("items");
                            if(items.containsKey("$ref")) {
                                String itemRef = items.getString("$ref");
                                String itemDef = itemRef.substring(14);
                                JSonObject itemDefJson = refMap.get(itemDef);
                                JSonObject childProperties = itemDefJson.getJSonObject("properties");
                                getRef(refMap,childProperties,resp,itemDef,itemDefJson);
                            }
                        }
                        respParameters.add(resp);
                    }
                }
            }
        }
        return respParameters;
    }
    
    
    public static List getRef(Map refMap,JSonObject childProperties,ResponseVo parentResp,String parentVoName,JSonObject childJson) {
        Set childSet = childProperties.keySet();
        List childResp = new ArrayList<>();
        for(String key : childSet) {
            JSonObject childMap = childProperties.getJSonObject(key);
            ResponseVo resp = new ResponseVo();
            resp.setName(key);
            resp.setFormat(childMap.getString("format"));
            resp.setDescription(childMap.getString("description"));
            String childType = childMap.getString("type");
            resp.setType(StringUtils.isNotBlank(childType)?childType:childJson.getString("type"));
            resp.setRequired(childMap.getBooleanValue("required"));
            childResp.add(resp);
            parentResp.setChildResp(childResp);
            if(childMap.containsKey("$ref")) {
                String childRef = childMap.getString("$ref");
                String childDef = childRef.substring(14);
                JSonObject childDefJson = refMap.get(childDef);
                JSonObject pro = childDefJson.getJSonObject("properties");
                //additionalProperties
                if(pro != null && !childDef.equalsIgnoreCase(parentVoName)) {
                    getRef(refMap,pro,resp,childDef,childDefJson);
                }
            }else if("array".equalsIgnoreCase(childType)) {
                JSonObject items = childMap.getJSonObject("items");
                if(items.containsKey("$ref")) {
                    String itemRef = items.getString("$ref");
                    String itemDef = itemRef.substring(14);
                    JSonObject itemDefJson = refMap.get(itemDef);
                    JSonObject pro = itemDefJson.getJSonObject("properties");
                    if(pro != null && !itemDef.equalsIgnoreCase(parentVoName)) {
                        getRef(refMap,pro,resp,itemDef,itemDefJson);
                    }
                }
            }
        }
        return childResp;
    }
    
    
    public static List getParameter(JSonArray parameters,Map refMap){
        List reqParameters = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(parameters)) {
            for(int i = 0; i < parameters.size(); i ++) {
                JSonObject paramJson = parameters.getJSonObject(i);
                ParameterVo param = JSON.parseObject(JSON.toJSonString(paramJson),ParameterVo.class);
                if(paramJson.containsKey("schema")) {
                    JSonObject schema = paramJson.getJSonObject("schema");
                    String schemaType = schema.getString("type");
                    String ref = "";
                    if(schema.containsKey("$ref")) {
                        ref = schema.getString("$ref");
                    }
                    if("array".equalsIgnoreCase(schemaType)){
                        JSonObject items = schema.getJSonObject("items");
                        if(items.containsKey("$ref")) {
                            ref = schema.getString("$ref");
                        }else {
                            List childParamList = new ArrayList<>();
                            ParameterVo childParam = new ParameterVo();
                            childParam.setName("");
                            childParam.setType(items.getString("type"));
                            childParamList.add(childParam);
                            param.setChildParam(childParamList);
                        }
                    }else {
                        param.setType(schemaType);
                    }
                    if(StringUtils.isNotBlank(ref)) {
                        String def = ref.substring(14);
                        JSonObject defJson = refMap.get(def);
                        if(defJson != null) {
                            param.setType(defJson.getString("type"));
                            JSonObject properties = defJson.getJSonObject("properties");
                            Set propertiesSet = properties.keySet();
                            List childParamList = new ArrayList<>();
                            for(String key : propertiesSet) {
                                ParameterVo childParam = new ParameterVo();
                                childParam.setName(key);
                                JSonObject proMap = properties.getJSonObject(key);
                                //根据type判断是否是array
                                String type = proMap.getString("type");
                                childParam.setDescription(StringUtils.isNotBlank(proMap.getString("description"))?proMap.getString("description"):"");
                                childParam.setType(StringUtils.isBlank(type)?"object":type);
                                childParam.setFormat(proMap.getString("format"));
                                childParam.setRequired(proMap.getBooleanValue("required"));
                                if(proMap.containsKey("$ref")) {
                                    String childRef = proMap.getString("$ref");
                                    String childDef = childRef.substring(14);
                                    JSonObject childDefJson = refMap.get(childDef);
                                    JSonObject childProperties = childDefJson.getJSonObject("properties");
                                    if(childProperties != null) {
                                        getParamRef(refMap,childProperties,childParam,childDef,childDefJson);
                                    }
                                }else if("array".equalsIgnoreCase(type)) {
                                    JSonObject items = proMap.getJSonObject("items");
                                    if(items.containsKey("$ref")) {
                                        String itemRef = items.getString("$ref");
                                        String itemDef = itemRef.substring(14);
                                        JSonObject itemDefJson = refMap.get(itemDef);
                                        JSonObject pro = itemDefJson.getJSonObject("properties");
                                        if(pro != null) {
                                            getParamRef(refMap,pro,childParam,itemDef,itemDefJson);
                                        }
                                    }
                                }
                                childParamList.add(childParam);
                                param.setChildParam(childParamList);
                            }
                        }
                    }
                }
                reqParameters.add(param);
            }
        }
        return reqParameters;
    }
    
    public static List getParamRef(Map refMap,JSonObject childProperties,ParameterVo parentResp,String parentVoName,JSonObject childJson) {
        List paramList = new ArrayList<>();
        Set childSet = childProperties.keySet();
        for(String key : childSet) {
            JSonObject childMap = childProperties.getJSonObject(key);
            ParameterVo resp = new ParameterVo();
            resp.setName(key);
            resp.setFormat(childMap.getString("format"));
            resp.setDescription(childMap.getString("description"));
            String childType = childMap.getString("type");
            resp.setType(StringUtils.isNotBlank(childType)?childType:childJson.getString("type"));
            resp.setRequired(childMap.getBooleanValue("required"));
            paramList.add(resp);
            parentResp.setChildParam(paramList);
            if(childMap.containsKey("$ref")) {
                String childRef = childMap.getString("$ref");
                String childDef = childRef.substring(14);
                JSonObject childDefJson = refMap.get(childDef);
                JSonObject pro = childDefJson.getJSonObject("properties");
                //additionalProperties
                if(pro != null && !childDef.equalsIgnoreCase(parentVoName)) {
                    getParamRef(refMap,pro,resp,childDef,childDefJson);
                }
            }else if("array".equalsIgnoreCase(childType)) {
                JSonObject items = childMap.getJSonObject("items");
                if(items.containsKey("$ref")) {
                    String itemRef = items.getString("$ref");
                    String itemDef = itemRef.substring(14);
                    JSonObject itemDefJson = refMap.get(itemDef);
                    JSonObject pro = itemDefJson.getJSonObject("properties");
                    if(pro != null && !itemDef.equalsIgnoreCase(parentVoName)) {
                        getParamRef(refMap,pro,resp,itemDef,itemDefJson);
                    }
                }
            }
        }
        return paramList;
    }
    
    
    public static Map getDefinitions(JSonObject swaggerJson){
        Map map= new HashMap<>();
        JSonObject definitions = swaggerJson.getJSonObject("definitions");
        Set definitionSet = definitions.keySet();
        for(String def : definitionSet) {
            map.put(def, definitions.getJSonObject(def));
        }
        return map;
    }
    
    public static void main(String[] args) {
        String respStr = HttpClientUtil.sendHttpGet("http://localhost:8080/v2/api-docs");
        //String respStr = "";

//swagger中的对象参数会以$ref的方式,fastjson默认会自己关联对象,导致解析时拿不到参数对象,需要DisableCircularReferenceDetect 来禁止循环引用
        JSonObject swaggerJson = JSON.parseObject(respStr,Feature.DisableCircularReferenceDetect);
        System.err.println(JSON.toJSonString(getPathInfo(swaggerJson),SerializerFeature.WriteNullStringAsEmpty));
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759265.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号