0
votes

Suppose I have an object of class io.swagger.models.Swagger, from the library io.swagger:swagger-models:1.5.24. How do I transform it into JSON?

My goal is to create a json file from our REST API definition. We're using Finch/Finagle in Scala, and this will be a brand new capability; I'd like it to be as generic as possible. I have an idea for the design, but it requires turning the Java model into JSON, and I haven't found that facility in Swagger yet.

This is swagger v2. Don't know what version of OpenAPI it is. It would be appreciated if there was also a method for generating swagger v3 and the related OpenAPI, but swagger v2 is an absolute necessity here.

1
It turns out to be very easy to do this with Gson. I'll post an answer to this question shortly. - Larry B.

1 Answers

0
votes

You can use the Gson library to encode the Java object. I used "com.google.code.gson" % "gson" % "2.8.6" in my build.sbt file.

The Scala code looks like this:

def getServerJson: String = {
    val gson = (new GsonBuilder).setPrettyPrinting().create
    val swag = new Swagger()

    val op = new Operation
    op.setVendorExtensions(null)
    op.setSummary("Updates a pet in the store with form data")
    op.consumes("application/x-www-form-urlencoded")
    val p = new Path
    p.setVendorExtensions(null)
    p.setPost(op)
    swag.path("/pet/{petId}",p)

    gson.toJson(swag)
  }

It's stateful, which is kind of annoying. Maybe there are immutable model objects that would be easier to manipulate in a functional program. That's not too big a deal, it satisfied my immediate need. The Json produced looks like:

{
  "swagger": "2.0",
  "paths": {
    "/pet/{petId}": {
      "post": {
        "summary": "Updates a pet in the store with form data",
        "consumes": [
          "application/x-www-form-urlencoded"
        ],
        "parameters": []
      }
    }
  }
}