swagger2导出api为word文档(java实现)[通俗易懂]

swagger2导出api为word文档(java实现)[通俗易懂]导出后的样式分析1,swagger2页面展示实际就是将返回的包含所有接口的json数据(在swagger界面,打开浏览器控制台即可看到该json数据)进行解析,并渲染到页面上。2,按照java面向对象思路分析,上述表格即为一个接口(一个单元),一共三个对象:Table.java、Request.java、Response.java。3,将原始swagger2的json数据进行…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

导出后的样式

swagger2导出api为word文档(java实现)[通俗易懂]

分析

1,swagger2 页面展示实际就是将返回的包含所有接口的json数据(在swagger界面,打开浏览器控制台即可看到该json数据)进行解析,并渲染到页面上。

2,按照java面向对象思路分析,上述表格即为一个接口(一个单元),一共三个对象:Table.java、Request.java、Response.java。

3,将原始swagger2的json数据进行解析、封装成上述三个java对象,然后再通过html渲染即可形成web版API文档。

4,将web版API文档另存为doc文件,即生成了api-doc文件。

实现

1,创建三个java对象

Table.java



package com.eden.yang.apidoc.vo;

import java.util.List;

/**
 * @FileName Table.java
 * @Description: 
 *
 * @Date 2019年3月18日 下午3:55:27
 * @author Eden
 * @version 1.0
 */
public class Table {

    /**
     * 大标题
     */
    private String title;
    /**
     * 小标题
     */
    private String tag;
    /**
     * url
     */
    private String url;

    /**
     * 响应参数格式
     */
    private String responseForm;

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

    /**
     * 请求体
     */
    private List<Request> requestList;

    /**
     * 返回体
     */
    private List<Response> responseList;

    /**
     * 请求参数
     */
    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<Request> getRequestList() {
        return requestList;
    }

    public void setRequestList(List<Request> requestList) {
        this.requestList = requestList;
    }

    public List<Response> getResponseList() {
        return responseList;
    }

    public void setResponseList(List<Response> responseList) {
        this.responseList = responseList;
    }

    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;
    }
}

Jetbrains全家桶1年46,售后保障稳定

Request.java



package com.eden.yang.apidoc.vo;

/**
 * @FileName Request.java
 * @Description: 
 *
 * @Date 2019年3月18日 下午3:56:29
 * @author Eden
 * @version 1.0
 */
public class Request {

    /**
     * 请求参数
     */
    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;
    }
}

Response.java



package com.eden.yang.apidoc.vo;

/**
 * @FileName Response.java
 * @Description: 
 *
 * @Date 2019年3月18日 下午3:57:10
 * @author Eden
 * @version 1.0
 */
public class Response {
    /**
     * 返回参数
     */
    private String description;

    /**
     * 参数名
     */
    private String name;

    /**
     * 说明
     */
    private String remark;

    public Response(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;
    }
}

2,swagger2原始json数据的解析(工具类)

ApiDocUtils.java



package com.eden.yang.apidoc.service;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import com.alibaba.fastjson.JSONObject;
import com.eden.yang.apidoc.vo.Request;
import com.eden.yang.apidoc.vo.Response;
import com.eden.yang.apidoc.vo.Table;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @FileName ApiDocUtils.java
 * @Description: 
 *
 * @Date 2019年3月18日 下午3:53:32
 * @author Eden
 * @version 1.0
 */
@Service
public class ApiDocUtils {

    @SuppressWarnings("rawtypes")
    public static List<Table> tableList() {
        List<Table> list = new LinkedList<Table>();
        try {
            URL resource = ClassUtils.getDefaultClassLoader().getResource("apidata.json");
            Map map = new ObjectMapper().readValue(resource, Map.class);
            //得到host,用于模拟http请求
//            String host = String.valueOf(map.get("host"));
            //解析paths
            @SuppressWarnings("unchecked")
            LinkedHashMap<String, LinkedHashMap> paths = (LinkedHashMap) map.get("paths");
            if (paths != null) {
                Iterator<Map.Entry<String, LinkedHashMap>> iterator = paths.entrySet().iterator();
                while (iterator.hasNext()) {
                    Table table = new Table();
                    List<Request> requestList = new LinkedList<Request>();
                    String requestType = "";

                    Map.Entry<String, LinkedHashMap> next = iterator.next();
                    String url = next.getKey();//得到url
                    @SuppressWarnings("unchecked")
                    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++) {
                            Request request = new Request();
                            @SuppressWarnings("unchecked")
                            LinkedHashMap<String, Object> param = (LinkedHashMap) parameters.get(i);
                            request.setDescription(String.valueOf(param.get("description")));
                            request.setName(String.valueOf(param.get("name")));
                            request.setType(String.valueOf(param.get("type")));
                            request.setParamType(String.valueOf(param.get("in")));
                            request.setRequire((Boolean) param.get("required"));
                            requestList.add(request);
                        }
                    }
                    //返回体,比较固定
                    List<Response> responseList = listResponse();
                    /*//模拟一次HTTP请求,封装请求体和返回体,如果是Restful的文档可以再补充
                    if (requestType.contains("post")) {
                        Map<String, String> stringStringMap = toPostBody(requestList);
                        table.setRequestParam(stringStringMap.toString());
                        String post = NetUtil.post(host + url, stringStringMap);
                        table.setResponseParam(post);
                    } else if (requestType.contains("get")) {
                        String s = toGetHeader(requestList);
                        table.setResponseParam(s);
                        String getStr = NetUtil.get(host + url + s);
                        table.setResponseParam(getStr);
                    }*/

                    //封装Table
                    table.setTitle(title);
                    table.setUrl(url);
                    table.setTag(tag);
                    table.setResponseForm("application/json");
                    table.setRequestType(StringUtils.removeEnd(requestType, "/"));
                    table.setRequestList(requestList);
                    table.setResponseList(responseList);
                    list.add(table);
                }
            }
            return list;

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


    //封装返回信息,可能需求不一样,可以自定义
    private static List<Response> listResponse() {
        List<Response> responseList = new LinkedList<Response>();
        responseList.add(new Response("结果说明信息", "msg", null));
        responseList.add(new Response("返回对象", "data", null));
        responseList.add(new Response("结果码", "code", null));
        return responseList;
    }

    //封装post请求体
    /*private Map<String, String> toPostBody(List<Request> list) {
        Map<String, String> map = new HashMap<>(16);
        if (list != null && list.size() > 0) {
            for (Request request : list) {
                String name = request.getName();
                String type = request.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 String toGetHeader(List<Request> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (Request request : list) {
                String name = request.getName();
                String type = request.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, "&");
    }*/

}

注意:

  1. apidata.json为存放swagger2原始json数据的文件;
  2. 调用tableList()方法生成特定的json数据,在下一步html渲染时传入;

3、渲染页面html代码:table.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="{CHARSET}">
		<title>table</title>
	</head>
	<body>
    </head>
        <div style="width:800px; margin: 0 auto" id="table">
               
        </div>
    </body>
    <script>
		
		var tableList = ;//该处输入上一步封装后的json数组
	

	
		(function table(){
    		
    		let html =[];
    		let cent=document.getElementById('table');
    		for(var i = 0; i < tableList.length; i++) {
    			let t=tableList[i];
    			html.push('<h4>'+t.title+'</h4>');
    			html.push('<h5>'+t.tag+'</h5>');
    			html.push('<table border="1" cellspacing="0" cellpadding="0" width="100%">');
    			
    			html.push('  <tr class="bg"><td colspan="6">'+t.tag+'</td></tr>');
    			html.push('  <tr><td>URL</td><td colspan="5">'+t.url+'</td></tr>');
    			html.push('  <tr><td>请求方式</td><td colspan="5">'+t.requestType+'</td></tr>');
    			html.push('  <tr><td>返回值类型</td><td colspan="5">'+t.responseForm+'</td></tr>');
				
				html.push('  <tr class="bg" align="center"><td>请求参数</td><td>参数名</td><td>数据类型</td><td>参数类型</td><td>是否必填</td><td>说明</td></tr>');
				for(var request in t.requestList){
                	let req=t.requestList[request];
                	let rq=req.require ? 'Y' : 'N';
                    html.push('<tr align="center">');
                    html.push('<td>'+req.description+'</td><td>'+req.name+'</td>');
                    html.push('<td>'+req.type+'</td>');
                    html.push('<td>'+req.paramType+'</td>');
                    html.push('<td>'+ rq + '</td>');
                    html.push('<td>'+req.remark+'</td></tr>');
            	};
            	
                html.push('<tr class="bg" align="center"><td>返回参数</td><td>参数名</td><td colspan="4">说明</td></tr>');
				
				for(var response in t.responseList){
					let res =t.responseList[response];
            		html.push('<tr align="center"><td>'+res.description+'</td><td>'+res.name+'</td><td colspan="4">'+res.remark+'</td></tr>');
                };
                html.push('<tr class="bg"><td colspan="6">示例</td></tr><tr class="specialHeight"><td class="bg">请求参数</td><td colspan="5">'+t.requestParam+'</td>');    	
                html.push('</tr><tr class="specialHeight"><td class="bg">返回值</td><td colspan="5">'+t.responseParam+'</td></tr>');
                
                html.push('</table><br>');
                    
			}
    		let htmtText =html.join("");
			cent.innerHTML=htmtText;
		})();
		</script>
		 <head>
        <title>tool</title>
        <style type="text/css">
            .bg {
            background-color: rgb(84, 127, 177);
            }

            tr {
            height: 20px;
            font-size: 12px;
            }

            .specialHeight {
            height: 40px;
            }
        </style>
</html>

4、生成web版API文档

将第二部中生成的封装后的json数组赋值给tableList,table()方法会在html加载时进行页面渲染。在浏览器中打开table.html即可看到web版API文档;

5、将页面另存为doc文件,结束!

参考:https://blog.csdn.net/zhuyu19911016520/article/details/85048271

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/234686.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号