swagger-ui api轉word文檔


 
思路:
 
        1.從swagger-ui.html頁面獲取json文檔
 
        2.java 解析json文檔
 
        3.前端發起請求,獲取解析信息,填充到頁面里
 
        4. 訪問html頁面,復制到word里
 
        
效果:
 
 
 
一。獲取json文檔
 
 
二。java代碼
 
2-1.實體類
 
package com.techvalley.djys.api.swagger.context;

public class SwaggerRequest {

    /**
     * 請求參數
     */
    private String description;

    /**
     * 參數名
     */
    private String name;

    /**
     * 數據類型
     */
    private String type;

    /**
     * 參數類型
     */
    private String paramType;

    /**
     * 是否必填
     */
    private Boolean require;

    /**
     * 說明
     */
    private String remark;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Boolean getRequire() {
        return require;
    }

    public void setRequire(Boolean require) {
        this.require = require;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getParamType() {
        return paramType;
    }

    public void setParamType(String paramType) {
        this.paramType = paramType;
    }
}
SwaggerRequest
package com.techvalley.djys.api.swagger.context;

public class SwaggerResponse {
    /**
     * 返回參數
     */
    private String description;

    /**
     * 參數名
     */
    private String name;

    /**
     * 說明
     */
    private String remark;

    public SwaggerResponse(String description, String name, String remark) {
        this.description = description;
        this.name = name;
        this.remark = remark;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}
SwaggerResponse
package com.techvalley.djys.api.swagger.context;

import java.util.List;

public class SwaggerTable {

    /**
     * 大標題
     */
    private String title;
    /**
     * 小標題
     */
    private String tag;
    /**
     * url
     */
    private String url;

    /**
     * 響應參數格式
     */
    private String responseForm;

    /**
     * 請求方式
     */
    private String requestType;

    /**
     * 請求體
     */
    private List<SwaggerRequest> swaggerRequestList;

    /**
     * 返回體
     */
    private List<SwaggerResponse> swaggerResponseList;

    /**
     * 請求參數
     */
    private String requestParam;

    /**
     * 返回值
     */
    private String responseParam;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getResponseForm() {
        return responseForm;
    }

    public void setResponseForm(String responseForm) {
        this.responseForm = responseForm;
    }

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public List<SwaggerRequest> getSwaggerRequestList() {
        return swaggerRequestList;
    }

    public void setSwaggerRequestList(List<SwaggerRequest> swaggerRequestList) {
        this.swaggerRequestList = swaggerRequestList;
    }

    public List<SwaggerResponse> getSwaggerResponseList() {
        return swaggerResponseList;
    }

    public void setSwaggerResponseList(List<SwaggerResponse> swaggerResponseList) {
        this.swaggerResponseList = swaggerResponseList;
    }

    public String getRequestParam() {
        return requestParam;
    }

    public void setRequestParam(String requestParam) {
        this.requestParam = requestParam;
    }

    public String getResponseParam() {
        return responseParam;
    }

    public void setResponseParam(String responseParam) {
        this.responseParam = responseParam;
    }
}
SwaggerTable

 

2-2.controller: 其中,json文件通過配置文件讀取
 
controller 方法代碼
    /**
     * 把swagger-ui里的API轉換為word文檔
     */
    @ApiOperation(value="把swagger-ui里的API轉換為word文檔")
    @RequestMapping(value = "/amap/swagger/toword", method = RequestMethod.POST)
    @ResponseBody
    public Object toword() throws Exception{
        List<SwaggerTable> list = SwaggerUtil.getTableList(swagger_json_file_path);
        return list;
    }

 

2-3.util
 
package com.techvalley.djys.api.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.techvalley.djys.api.swagger.context.SwaggerRequest;
import com.techvalley.djys.api.swagger.context.SwaggerResponse;
import com.techvalley.djys.api.swagger.context.SwaggerTable;
import com.techvalley.microservice.commons.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.*;

public class SwaggerUtil {

    public static List<SwaggerTable> getTableList(String filePath) throws Exception{
        List<SwaggerTable> list = new LinkedList();
        try {
            File file = new File(filePath);
            String json = jsonRead(file);
            JsonNode jsonNode = JsonUtil.readTree(json);
            RestTemplate restTemplate = new RestTemplate();
            Map map = JsonUtil.string2Object(json,Map.class);
            //得到host,用於模擬http請求
            String host = String.valueOf(map.get("host"));
            String basePath = String.valueOf(map.get("basePath"));
            //解析paths
            LinkedHashMap<String, LinkedHashMap> paths = (LinkedHashMap) map.get("paths");
            if (paths != null) {
                Iterator<Map.Entry<String, LinkedHashMap>> iterator = paths.entrySet().iterator();
                while (iterator.hasNext()) {
                    SwaggerTable swaggerTable = new SwaggerTable();
                    List<SwaggerRequest> swaggerRequestList = new LinkedList<SwaggerRequest>();
                    String requestType = "";

                    Map.Entry<String, LinkedHashMap> next = iterator.next();
                    String url = next.getKey();//得到url
                    LinkedHashMap<String, LinkedHashMap> value = next.getValue();
                    //得到請求方式,輸出結果類似為 get/post/delete/put 這樣
                    Set<String> requestTypes = value.keySet();
                    for (String str : requestTypes) {
                        requestType += str + "/";
                    }
                    Iterator<Map.Entry<String, LinkedHashMap>> it2 = value.entrySet().iterator();
                    //解析請求
                    Map.Entry<String, LinkedHashMap> get = it2.next();//得到get
                    LinkedHashMap getValue = get.getValue();
                    String title = (String) ((List) getValue.get("tags")).get(0);//得到大標題
                    String tag = String.valueOf(getValue.get("summary"));
                    //請求體
                    ArrayList parameters = (ArrayList) getValue.get("parameters");
                    if (parameters != null && parameters.size() > 0) {
                        for (int i = 0; i < parameters.size(); i++) {
                            SwaggerRequest swaggerRequest = new SwaggerRequest();
                            LinkedHashMap<String, Object> param = (LinkedHashMap) parameters.get(i);
                            swaggerRequest.setDescription(String.valueOf(param.get("description")));
                            swaggerRequest.setName(String.valueOf(param.get("name")));
                            swaggerRequest.setType(String.valueOf(param.get("type")));
                            swaggerRequest.setParamType(String.valueOf(param.get("in")));
                            swaggerRequest.setRequire((Boolean) param.get("required"));
                            swaggerRequestList.add(swaggerRequest);
                        }
                    }
                    //返回體,比較固定
                    List<SwaggerResponse> swaggerResponseList = listResponse();
                    //模擬一次HTTP請求,封裝請求體和返回體,如果是Restful的文檔可以再補充

                    if (requestType.contains("post")) {
                        Map<String, String> stringStringMap = toPostBody(swaggerRequestList);
                        swaggerTable.setRequestParam(stringStringMap.toString());

                        HttpHeaders headers = new HttpHeaders();

                        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(stringStringMap, headers);
//                        String post = NetUtil.post(host + url, stringStringMap);
//                        String post = restTemplate.postForObject("http://"+host +basePath + url, request,String.class);
//                        swaggerTable.setResponseParam(post);
                    } else if (requestType.contains("get")) {
                        String s = toGetHeader(swaggerRequestList);
                        swaggerTable.setResponseParam(s);
//                        String getStr = NetUtil.get(host + url + s);
//                        String getStr = restTemplate.getForObject(host +basePath + url + s, String.class);
//                        swaggerTable.setResponseParam(getStr);
                    }

                    //封裝Table
                    swaggerTable.setTitle(title);
                    swaggerTable.setUrl(url);
                    swaggerTable.setTag(tag);
                    swaggerTable.setResponseForm("application/json");
                    swaggerTable.setRequestType(StringUtils.removeEnd(requestType, "/"));
                    swaggerTable.setSwaggerRequestList(swaggerRequestList);
                    swaggerTable.setSwaggerResponseList(swaggerResponseList);
                    list.add(swaggerTable);
                }
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //封裝返回信息,可能需求不一樣,可以自定義
    private static List<SwaggerResponse> listResponse() {
        List<SwaggerResponse> swaggerResponseList = new LinkedList<SwaggerResponse>();
        swaggerResponseList.add(new SwaggerResponse("受影響的行數", "counts", null));
        swaggerResponseList.add(new SwaggerResponse("結果說明信息", "msg", null));
        swaggerResponseList.add(new SwaggerResponse("是否成功", "success", null));
        swaggerResponseList.add(new SwaggerResponse("返回對象", "data", null));
        swaggerResponseList.add(new SwaggerResponse("錯誤代碼", "errCode", null));
        return swaggerResponseList;
    }

    //封裝post請求體
    private static Map<String, String> toPostBody(List<SwaggerRequest> list) {
        Map<String, String> map = new HashMap<>(16);
        if (list != null && list.size() > 0) {
            for (SwaggerRequest swaggerRequest : list) {
                String name = swaggerRequest.getName();
                String type = swaggerRequest.getType();
                switch (type) {
                    case "string":
                        map.put(name, "string");
                        break;
                    case "integer":
                        map.put(name, "0");
                        break;
                    case "double":
                        map.put(name, "0.0");
                        break;
                    default:
                        map.put(name, "null");
                        break;
                }
            }
        }
        return map;
    }

    //封裝get請求頭
    private static String toGetHeader(List<SwaggerRequest> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (SwaggerRequest swaggerRequest : list) {
                String name = swaggerRequest.getName();
                String type = swaggerRequest.getType();
                switch (type) {
                    case "string":
                        stringBuffer.append(name+"&=string");
                        break;
                    case "integer":
                        stringBuffer.append(name+"&=0");
                        break;
                    case "double":
                        stringBuffer.append(name+"&=0.0");
                        break;
                    default:
                        stringBuffer.append(name+"&=null");
                        break;
                }
            }
        }
        String s = stringBuffer.toString();
        if ("".equalsIgnoreCase(s)){
            return "";
        }
        return "?" + StringUtils.removeStart(s, "&");
    }

    private static String jsonRead(File file){
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {

        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();
    }
}
SwaggerUtil

 

2-4.html頁面: 其中jquery.js和vue.js是在線引用(當然也可以引用自己項目中的)
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>接口文檔</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
  </head>

  <body>
    <div id="app">
      <div class="item" v-for="(item,i) in data" :key="i">
        <h4>{{ i + 1 }}、{{ item.title }}:{{ item.url }}</h4>
        <table cellspacing="0" cellpadding="0" border="1" id="out-table">
          <thead class="bg">
            <tr>
              <th colspan="6">{{ item.tag }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>URL</td>
              <td colspan="5">{{ item.url }}</td>
            </tr>
            <tr>
              <td>請求方式</td>
              <td colspan="5">{{ item.responseForm }}</td>
            </tr>
            <tr>
              <td>返回值類型</td>
              <td colspan="5">{{ item.requestType }}</td>
            </tr>
            <tr class="bg">
              <td>請求參數</td>
              <td>參數名</td>
              <td>數據類型</td>
              <td>參數類型</td>
              <td>是否必填</td>
              <td>說明</td>
            </tr>
            <tr v-for="(r,inIndex) in item.swaggerRequestList">
              <td>{{ r.description }}</td>
              <td>{{ r.name }}</td>
              <td>{{ r.type }}</td>
              <td>{{ r.paramType }}</td>
              <td>{{ r.require }}</td>
              <td>{{ r.remark }}</td>
            </tr>
            <tr class="bg">
              <td>返回參數</td>
              <td>參數名</td>
              <td colspan="4">說明</td>
            </tr>
            <tr v-for="(r,inIndex) in item.swaggerResponseList">
              <td>{{ r.description }}</td>
              <td>{{ r.name }}</td>
              <td colspan="4">{{ r.remark }}</td>
            </tr>
            <tr class="bg">
              <td colspan="6">示例</td>
            </tr>
            <tr>
              <td>請求參數</td>
              <td colspan="5">{{ item.requestParam }}</td>
            </tr>
            <tr>
              <td>返回值</td>
              <td colspan="5">{{ item.responseParam }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </body>
</html>
<script>
  var app = new Vue({
    el: "#app",
    data() {
      return {
        data: []
      };
    },
    created() {
      let self = this;
      $.ajax({
        type: "POST",
        url: "/techvalley-djys/amap/swagger/toword", //todo http://192.168.22.202:9999/techvalley-djys/amap/swagger/toword
        data: "",
        dataType: "json",
        mimeType: "multipart/form-data",
        cache: false,
        processData: false,
        contentType: false,
        success: function(data) {
          self.data = data;
        }
      });
    }
  });
</script>
<style>
  .item {
    width: 800px;
    margin: 0 auto;
  }
  table {
    width: 100%;
  }
  table td {
    padding: 10px;
  }
  table tr td:first-child {
    min-width: 80px;
  }
  .item + .item {
    margin-top: 20px;
  }
  .bg {
    color: #fff;
    background: #5079a9;
  }
</style>
swaggerToApi.html

 

 
3.訪問html頁面:根據自己頁面放置位置進行訪問
 
 
 
4. 轉換為word
 
全選---->復制---->粘貼
 
5.手動整理word,效果如下
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM