10

I need to read, modify and re-generate a JSON/YAML swagger file documentation. I have deserialized a JSON file with Swagger Parser and I have a Swagger Java Object with the original JSON data mapped correctly.

Now, I need to modify the Swagger Java object, and generate a JSON or YAML file with the done modifications.

Is there a way to do that?

Summary:

File fileJSON = FileUtils.toFile(getClass().getResource("example-api-rest.json"));

Swagger swagger = new SwaggerParser().read(fileJSON.getPath()); //Got it!
...
swagger.editWhatever
...
//Here I need to generate the JSON or YAML again

Thanks.

1 Answer 1

15

To generate OpenAPI 2.0 JSON:

import io.swagger.util.Json;

String jsonOutput = Json.pretty(swagger);

To generate YAML:

import io.swagger.util.Yaml;

String yamlOutput = Yaml.pretty().writeValueAsString(swagger);

The io.swagger.util package is part of Swagger Core, which is one of the dependencies of Swagger Parser.


If your spec is OpenAPI 3.0, use Json.pretty() and Yaml.pretty() from the io.swagger.v3.core.util package.

In case of OpenAPI 3.1, use Json31.pretty() and Yaml31.pretty() from io.swagger.v3.core.util; see here about the differences in OAS 3.1 vs 3.0 (de)serialization.

3
  • What if I don't want it pretty. Is there a way to do this without parsing the string to Java and then back to Json?
    – TheClassic
    Commented Dec 13, 2022 at 14:09
  • @TheClassic can you please clarify what you're trying to do in the first place? I'm not sure I understand.
    – Helen
    Commented Dec 13, 2022 at 15:06
  • 1
    @TheClassic If you are asking whether the io.swagger.util.Json class has a non-pretty output method - this class uses Jackson ObjectMapper internally (com.fasterxml.jackson.databind.ObjectMapper). So instead of using io.swagger.util.Json, you can create and use your own Jackson ObjectMapper instance with the desired serialization settings.
    – Helen
    Commented Dec 13, 2022 at 15:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.