Groovy web console

subscribe to the feed Subscribe
to this
site
JSONToSwagger (via #groovywebconsole)
tweet this snippet Tweet
this
script

JSONToSwagger

Published 3 months ago by nothing with tags swagger json
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

class JSONToSwagger {
    // space definitions
    final static String space1 = " "
    final static String space2 = "  "
    final static String space4 = "    "
    final static String space6 = "      "

    // content string definitions
    static String contentString = ""
    static String referenceString = ""

    // important notes:
    // 1. only support for single-level or two-level json
    // 2. only define two types: string, boolean
    // 3. only convert to yaml format
    static void main(String[] args) {
        // settings
        String title = "Case" // top definition name
        String jsonString = """
{
  "origin": "web",
  "afterIncOrderId": "12345678",
  "billToAddress": {
    "billToAddressLine": "Theodore Lowe Ap #867-859 Sit Rd.",
    "billToAddressCityCopy": "Azusa",
    "billToAddressStateCopy": "NY",
    "billToAddressPostalCodeCopy": "39531",
    "billToAddressCountryCopy": "US"
  },
  "business": {
    "company ": "Seagate",
    "vatNumber": "VN123456"
  },
  "currencyCode ": "USD",
  "dataReturnInfo": {
    "dataReturnType": "I want my recovered data returned on a 4TB external Seagate Hard Drive",
    "mediaReturnOSFormat": "MAC",
    "notificationSelected": "Case status via email"
  },
  "deviceInfo": {
    "device": "RAID",
    "numRaidDevices": "2",
    "numRaidWhatType": "1",
    "serialNum": "SN123456"
  },
  "deviceRecoveryInfo": {
    "dataEncrypted": true,
    "importantFile": "FileA",
    "legalAction": true,
    "password1": "password1",
    "password2": "password2",
    "whatHappend": "Data overwritten"
  },
  "doSelfShipping": false,
  "lablocation ": "OKC Lab",
  "language": "en-us",
  "optOut": true,
  "promoCode": "PC123456",
  "shippingAddress": {
    "address": "Haviva Holcomb P.O. Box 642 3450 In Road",
    "city ": "Isle of Palms",
    "country": "US",
    "email ": "johndoe@fulcrm.com",
    "firstName": "John",
    "lastName": "Doe",
    "phone ": 88888888,
    "state": "NY",
    "zip ": "03828"
  }
}
"""
        // output
        String result = drawSwagger(jsonString, title)
        println result
    }

    static String drawSwagger(String jsonString, String title) {
        def jsonSlurper = new JsonSlurper()
        def jsonObject = jsonSlurper.parseText(jsonString)

        contentString = drawTitle(contentString, title)
        contentString = drawObject(contentString, jsonObject, false)
        
        return "$referenceString$contentString"
    }

    static String drawProperty(String content, String key, String value, String type, boolean isTitle) {
        if (isTitle && type == "object") {
            content += "\n$key:\n${space2}type:${space1}$type"
        } else if (isTitle && type != "object") {
            content += "\n${space4}$key:\n${space6}type:${space1}$type"
        } else {
            content += "\n${space4}$key:\n${space6}type:${space1}$type\n${space6}example:${space1}$value"
        }
        return content
    }

    static String drawTitle(String content, String key) {
        content = drawProperty(content, key.capitalize(), "", "object", true)
        content += "\n${space2}properties:"
        return content
    }

    static String drawReference(String content, String key, value) {
        content += "\n${space4}$key:\n${space6}\$ref: '#/definitions/${key.capitalize()}'"
        referenceString = drawTitle(referenceString, key)
        referenceString = drawObject(referenceString, value, false)
        return content
    }

    static String drawObject(String content, object, boolean createRef) {
        object.each { String key, value ->
            if (value instanceof Map) {
                content = drawReference(content, key, value)
            } else if (isBoolean(value as String)) {
                content = drawProperty(content, key, value as String, "boolean", createRef)
            } else {
                content = drawProperty(content, key, value as String, "string", createRef)
            }
        }
        return content
    }

    static boolean isBoolean(String value) {
        boolean isBoolean = value == "true" || value == "false"
        return isBoolean
    }
}