Android 使用Swagger快速生成接口和Model类

Android 使用Swagger快速生成接口和Model类_第1张图片
image.png

添加上图中的几个文件

swagger-codegen-cli.jar 下载地址

目前最新swagger-codegen-cli-3.0.0-20170824.041313-2.jar

build.sh文件

#!/bin/sh

wget --no-check-certificate -O ./swagger.json https://xxx.xxx.xxx/xxx/api-docs
php ./format_api.php
java -jar ./swagger-codegen-cli.jar generate -i ./docs.json -l java -c ./config.json -o ../api-client

其中 https://xxx.xxx.xx/xx/api-docs是你们公司Swagger接口文档的地址

config.json文件

{
    "library": "retrofit2",//生成的代码支付的类,有jersey1、jersey2、okhttp-gson、resttemplate、resteasy、feign、retrofit、retrofit2
    "useRxJava2": "true",//是否使用rxjava2的方式调用接口
    "developerName": "HBoy",//开发者名称
    "developerEmail": "",//邮箱
    "developerOrganization": "app.com",
    "invokerPackage": "com.app.android.client",//项目的包名
    "modelPackage": "com.app.android.entity",//
    "apiPackage": "com.app.android.api",//生成api的包名
    "groupId":"com.app.android",//model类包名
    "artifactId": "client",
    "serializableModel": true
}

format_api.php文件

parse(file_get_contents('./swagger.yaml'));

$paths = $content['paths'];
global $definitions;
$definitions = $content['definitions'];

foreach ($paths as $key => $path) {
    if (strpos($key, '/web/') !== false) {
        unset($paths[$key]);
    } else {
        $paths[$key] = handlePath($key, $path);
    }
}

$content['paths'] = $paths;
$content['definitions'] = $definitions;

file_put_contents('./docs.json', json_encode($content));

function handlePath($url, $path) {
    foreach ($path as $key => $request) {
        $path[$key] = handleRequest( $url ,$key, $request);
    }

    return $path;
}

function handleRequest($path, $method, $request) {

    $request['operationId'] = basename($path, '.do').'Using'.strtoupper($method);

    if ($request['parameters']) {
        $parameters = [];
        foreach ($request['parameters'] as $key => $parameter) {
            $parameter = handleParameter($parameter);
            unset($request['parameters'][$key]);
            if ($parameter) {
                $parameters[] = $parameter;
            }
        }

        if (empty($parameters)) {
            unset($request['parameters']);
        } else {
            $request['parameters'] = $parameters;
        }
    }

    if ($request['responses']) {
        $responses = [];
        foreach ($request['responses'] as $key => $response) {
            $response = handleResponse($path, $method, $response);
            if ($response) {
                $responses[$key] = $response;
            }
        }
        if (empty($responses)) {
            unset($request['responses']);
        } else {
            $request['responses'] = $responses;
        }
    }
    
    return $request;
}

function handleResponse($path, $method, $response) {
    if (isset($response['schema']) && isset($response['schema']['type'])  && $response['schema']['type'] == 'object' && isset($response['schema']['properties']) ) {
        $paths = explode("/",$path); 
        $name = "";
        foreach ($paths as $item) {
            $name .= ucfirst($item);
        }
        $name.=ucfirst($method);
        $name .= "Response";
        $definition = $response['schema'];
        global $definitions; 
        $definitions[$name] = $definition;
        $response['schema']= ['$ref'=> "#/definitions/".$name];
    }

    return $response;
}

function handleParameter($parameter) {
    $value = array_values($parameter);

    if(isset($parameter['$ref']) ) {
        $ref = $parameter['$ref'];
        if ($ref == '#/parameters/AppKey' || $ref == '#/parameters/Timestamp' || $ref== '#/parameters/Signature' || $ref == '#/parameters/AccessToken') {
            return null;
        }
    }

    if( isset($parameter['name']) && $parameter['name'] == 'access_token') {
        return null;
    }

    return $parameter;
}

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}

format_api.php文件的作用是将下载下来的swagger.json(接口文档格式化一下,主要是去掉一些接口方法后面会莫名加上_7 、_9、_15这种结尾,而且会变化)格式化成docs.json文件。

最后通过运行build.sh会自动生成client这个module,最后在主工程添加引用compile project(':api-client'),并在settings.gradle中添加,完事。

生成的接口是retrofit格式的如下,然后在需要的地方调用即可,当然可以再配合RxJava调用,看各人喜好:

Android 使用Swagger快速生成接口和Model类_第2张图片
image.png

你可能感兴趣的:(Android 使用Swagger快速生成接口和Model类)