Swagger Codegen 自動生成Retrofit 代碼

swagger是一個統一前后端的好工具,可以使用它來規劃客戶端的API訪問規劃,可以用來規劃服務端接口的開發。這篇文章我介紹一下如何使用swagger codegen自動生成retrofit代碼(rxjava2)。

如何使用swagger-codegen-cli生成retrofit 代碼

開門見山,不BB,看看怎么自動生成代碼

  • 下載swagger-codegen-cli.jar

    首先要我們先去下載swagger-codegen-cli.jar 包,寫這篇文章的時候最新是3.0.0版本,下載地址在這里喲 ,下載下來的的文件名帶有和版號,“swagger-codegen-cli-3.0.0-20170727.135949-1.jar”。覺得文件名太長,輸入命令太累,而且容易出錯誤,所有我把它重命名了,“swagger-codegen-cli.jar”,當然你也可以根據自己喜歡重命名或不重命名它。

  • maven

    官方和許多網友說要安裝maven,那就去下個maven,安裝它,并把maven路徑添加到環境變量path中。其實我好像沒有安裝maven的,但是我的retrofit代碼還是生成成功了。

  • 寫配制文件config.json

    新建個文件命名為config.json,在config.json文件中添加如下內容

    {
      "library": "retrofit2",
      "useRxJava2": "true",
      "developerName": "leix",
      "developerEmail": "",
      "developerOrganization": "albani.com",
      "invokerPackage": "com.albani.app",
      "modelPackage": "com.albani.app.data.entity",
      "apiPackage": "com.albani.app.data.api",
      "artifactId": "swagger-petstore-retrofit2"
    }
    
  • 準備swagger.json

    json文件和yml文件都是可以的,所以用editor生成swagger.json或swagger.yml

  • 見證奇跡了

    windows下運行cmd,輸入如下命令:

    java -jar swagger-codegen-cli.jar generate -i swagger.json -o client -l java -c config.json
    

    回車,奇跡發生了,在你的client文件夾下生成了retrofit 網絡請求代碼,當然這個代碼可能還是要根據需要做些小調整的。。

簡單解析一下swagger-codegen的用法吧

上面代碼已經生成了,但它是怎么動作的呢?在github上的文章說的比較清楚,下面來簡單說說吧!

  • 在cmd中輸入如下命名,獲取幫助說明

    java -jar swagger-codegen-cli.jar help
    

    命令行打印出幫助說明

    usage: swagger-codegen-cli <command> [<args>]
    The most commonly used swagger-codegen-cli commands are:
        config-help   Config help for chosen lang
        generate      Generate code with chosen lang
        help          Display help information
        langs         Shows available langs
        meta          MetaGenerator. Generator for creating a new template set and configuration for Codegen.  The output will be based on the language you specify, and includes default templates to include.
        validate      Validate specification
        version       Show version information
    See 'swagger-codegen-cli help <command>' for more information on a specific
    command.
    
  • generate 使用說明

    java -jar swagger-codegen-cli.jar generate help
    

    命令行將打出generate相關的幫助說明

    NAME
            swagger-codegen-cli generate - Generate code with chosen lang
    SYNOPSIS
            swagger-codegen-cli generate
                    [(-a <authorization> | --auth <authorization>)]
                    [--additional-properties <additional properties>...]
                    [--api-package <api package>] [--artifact-id <artifact id>]
                    [--artifact-version <artifact version>]
                    [(-c <configuration file> | --config <configuration file>)]
                    [-D <system properties>...] [--git-repo-id <git repo id>]
                    [--git-user-id <git user id>] [--group-id <group id>]
                    [--http-user-agent <http user agent>]
                    (-i <spec file> | --input-spec <spec file>)
                    [--ignore-file-override <ignore file override location>]
                    [--import-mappings <import mappings>...]
                    [--instantiation-types <instantiation types>...]
                    [--invoker-package <invoker package>]
                    (-l <language> | --lang <language>)
                    [--language-specific-primitives <language specific primitives>...]
                    [--library <library>] [--model-name-prefix <model name prefix>]
                    [--model-name-suffix <model name suffix>]
                    [--model-package <model package>]
                    [(-o <output directory> | --output <output directory>)]
                    [--release-note <release note>] [--remove-operation-id-prefix]
                    [--reserved-words-mappings <reserved word mappings>...]
                    [(-s | --skip-overwrite)]
                    [(-t <template directory> | --template-dir <template directory>)]
                    [--type-mappings <type mappings>...] [(-v | --verbose)]
    OPTIONS
            -a <authorization>, --auth <authorization>
                adds authorization headers when fetching the swagger definitions
                remotely. Pass in a URL-encoded string of name:header with a comma
                separating multiple values
            --additional-properties <additional properties>
                sets additional properties that can be referenced by the mustache
                templates in the format of name=value,name=value. You can also have
                multiple occurrences of this option.
            --api-package <api package>
                package for generated api classes
            --artifact-id <artifact id>
                artifactId in generated pom.xml
            --artifact-version <artifact version>
                artifact version in generated pom.xml
            -c <configuration file>, --config <configuration file>
                Path to json configuration file. File content should be in a json
                format {"optionKey":"optionValue", "optionKey1":"optionValue1"...}
                Supported options can be different for each language. Run
                config-help -l {lang} command for language specific config options.
            -D <system properties>
                sets specified system properties in the format of
                name=value,name=value (or multiple options, each with name=value)
            --git-repo-id <git repo id>
                Git repo ID, e.g. swagger-codegen.
            --git-user-id <git user id>
                Git user ID, e.g. swagger-api.
            --group-id <group id>
                groupId in generated pom.xml
            --http-user-agent <http user agent>
                HTTP user agent, e.g. codegen_csharp_api_client, default to
                'Swagger-Codegen/{packageVersion}}/{language}'
            -i <spec file>, --input-spec <spec file>
                location of the swagger spec, as URL or file (required)
            --ignore-file-override <ignore file override location>
                Specifies an override location for the .swagger-codegen-ignore file.
                Most useful on initial generation.
            --import-mappings <import mappings>
                specifies mappings between a given class and the import that should
                be used for that class in the format of type=import,type=import. You
                can also have multiple occurrences of this option.
            --instantiation-types <instantiation types>
                sets instantiation type mappings in the format of
                type=instantiatedType,type=instantiatedType.For example (in Java):
                array=ArrayList,map=HashMap. In other words array types will get
                instantiated as ArrayList in generated code. You can also have
                multiple occurrences of this option.
            --invoker-package <invoker package>
                root package for generated code
            -l <language>, --lang <language>
                client language to generate (maybe class name in classpath,
                required)
            --language-specific-primitives <language specific primitives>
                specifies additional language specific primitive types in the format
                of type1,type2,type3,type3. For example:
                String,boolean,Boolean,Double. You can also have multiple
                occurrences of this option.
            --library <library>
                library template (sub-template)
            --model-name-prefix <model name prefix>
                Prefix that will be prepended to all model names. Default is the
                empty string.
            --model-name-suffix <model name suffix>
                Suffix that will be appended to all model names. Default is the
                empty string.
            --model-package <model package>
                package for generated models
            -o <output directory>, --output <output directory>
                where to write the generated files (current dir by default)
            --release-note <release note>
                Release note, default to 'Minor update'.
            --remove-operation-id-prefix
                Remove prefix of operationId, e.g. config_getId => getId
            --reserved-words-mappings <reserved word mappings>
                specifies how a reserved name should be escaped to. Otherwise, the
                default _<name> is used. For example id=identifier. You can also
                have multiple occurrences of this option.
            -s, --skip-overwrite
                specifies if the existing files should be overwritten during the
                generation.
            -t <template directory>, --template-dir <template directory>
                folder containing the template files
            --type-mappings <type mappings>
                sets mappings between swagger spec types and generated code types in
                the format of swaggerType=generatedType,swaggerType=generatedType.
                For example: array=List,map=Map,string=String. You can also have
                multiple occurrences of this option.
            -v, --verbose
                verbose mode
    

    講一下我們用到的幾個參數的意思

    • -i 表示輸入的文件,editor生成的設計文件路徑,如:-i d:/swagger/swagger.json

    • -o 代碼生成目錄,swagger codegen把代碼生成到什么地方,如:-o d:/swagger/client

    • -l 生成代碼語言,我們是生成java,如:-l java

    • -c 配置文件,配制文件路徑,如:-c d:/swagger/config.json

  • config說明

    寫了個config.json文件,但是這個文件里的設置到底是些什么鬼呢?下面我們來看看config的幫助,輸入以下命令獲取幫助說明

    java -jar swagger-codegen-cli.jar config-help -l java
    

    命令行打印出幫助說明

    CONFIG OPTIONS
            sortParamsByRequiredFlag
                Sort method arguments to place required parameters before optional parameters. (Default: true)
            ensureUniqueParams
                Whether to ensure parameter names are unique in an operation (rename parameters that are not). (Default: true)
            allowUnicodeIdentifiers
                boolean, toggles whether unicode identifiers are allowed in names or not, default is false (Default: false)
            modelPackage
                package for generated models
            apiPackage
                package for generated api classes
            invokerPackage
                root package for generated code
            groupId
                groupId in generated pom.xml
            artifactId
                artifactId in generated pom.xml
            artifactVersion
                artifact version in generated pom.xml
            artifactUrl
                artifact URL in generated pom.xml
            artifactDescription
                artifact description in generated pom.xml
            scmConnection
                SCM connection in generated pom.xml
            scmDeveloperConnection
                SCM developer connection in generated pom.xml
            scmUrl
                SCM URL in generated pom.xml
            developerName
                developer name in generated pom.xml
            developerEmail
                developer email in generated pom.xml
            developerOrganization
                developer organization in generated pom.xml
            developerOrganizationUrl
                developer organization URL in generated pom.xml
            licenseName
                The name of the license
            licenseUrl
                The URL of the license
            sourceFolder
                source folder for generated code
            localVariablePrefix
                prefix for generated code members and local variables
            serializableModel
                boolean - toggle "implements Serializable" for generated models (Default: false)
            bigDecimalAsString
                Treat BigDecimal values as Strings to avoid precision loss. (Default: false)
            fullJavaUtil
                whether to use fully qualified name for classes under java.util. This option only works for Java API client (Default: false)
            hideGenerationTimestamp
                hides the timestamp when files were generated
            withXml
                whether to include support for application/xml content type. This option only works for Java API client (resttemplate) (Default: false)
            dateLibrary
                Option. Date library to use
                    joda - Joda (for legacy app only)
                    legacy - Legacy java.util.Date (if you really have a good reason not to use threetenbp
                    java8-localdatetime - Java 8 using LocalDateTime (for legacy app only)
                    java8 - Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets "java8" to true
                    threetenbp - Backport of JSR310 (preferred for jdk < 1.8)
            java8
                Option. Use Java8 classes instead of third party equivalents
                    true - Use Java 8 classes such as Base64
                    false - Various third party libraries as needed
            useRxJava
                Whether to use the RxJava adapter with the retrofit2 library. (Default: false)
            useRxJava2
                Whether to use the RxJava2 adapter with the retrofit2 library. (Default: false)
            parcelableModel
                Whether to generate models for Android that implement Parcelable with the okhttp-gson library. (Default: false)
            usePlay24WS
                Use Play! 2.4 Async HTTP client (Play WS API) (Default: false)
            supportJava6
                Whether to support Java6 with the Jersey1 library. (Default: false)
            useBeanValidation
                Use BeanValidation API annotations (Default: false)
            performBeanValidation
                Perform BeanValidation (Default: false)
            useGzipFeature
                Send gzip-encoded requests (Default: false)
            useRuntimeException
                Use RuntimeException instead of Exception (Default: false)
            library
                library template (sub-template) to use (Default: okhttp-gson)
                    jersey1 - HTTP client: Jersey client 1.19.4. JSON processing: Jackson 2.8.9. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
                    feign - HTTP client: OpenFeign 9.4.0. JSON processing: Jackson 2.8.9
                    jersey2 - HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.9
                    okhttp-gson - HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.8.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
                    retrofit - HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.
                    retrofit2 - HTTP client: OkHttp 3.8.0. JSON processing: Gson 2.6.1 (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)
                    resttemplate - HTTP client: Spring RestTemplate 4.3.9-RELEASE. JSON processing: Jackson 2.8.9
                    resteasy - HTTP client: Resteasy client 3.1.3.Final. JSON processing: Jackson 2.8.9
    

    介紹下我們用到的幾個主要參數

    • library,生成的代碼支付的類,有jersey1、jersey2、okhttp-gson、resttemplate、resteasy、feign、retrofit、retrofit2等幾種類型,我們選擇的retrofit2
    • developerName,開發者名字,會出現在代碼文件里
    • developerEmail,開發者郵箱,會出現在代碼文件里
    • developrOrganization,開發者組織,會出現在代碼里
    • invokerPackage,項目的包名
    • apiPackage,生成的***Api.java文件的包名
    • modelPackage,生成的數據模型java文件包名
    • dateLibrary,時間使用的類開
    • useRxJava,是否使用rxjava生成api接口
    • useRxJava2,是否使用rxjava2的方式調用接口,在這里我們設為true
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,646評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,595評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,560評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,035評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,814評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,224評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,301評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,444評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,988評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,804評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,998評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,544評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,237評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,665評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,927評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,706評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,993評論 2 374

推薦閱讀更多精彩內容