diff --git a/examples/pets-cli/pom.xml b/examples/pets-cli/pom.xml index 86f5f10..ae249bd 100644 --- a/examples/pets-cli/pom.xml +++ b/examples/pets-cli/pom.xml @@ -3,7 +3,7 @@ 4.0.0 rickwporter.prettytable pets-cli - 0.1.0 + 0.1.1 pets-cli CLI for the OpenAPI Petstore, rendered with prettytable. @@ -13,7 +13,7 @@ 4.7.6 2.18.2 5.14.1 - 1.0.0 + 1.1.0 3.6.0 diff --git a/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java index a8d9b8b..7358566 100644 --- a/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java +++ b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java @@ -12,6 +12,11 @@ import java.util.Set; import java.util.concurrent.Callable; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.ObjectMapper; + import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Model.CommandSpec; @@ -20,9 +25,8 @@ import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ScopeType; import picocli.CommandLine.Spec; - import rickwporter.prettytable.PrettyTable; -import rickwporter.prettytable.PrettyTable.OutputFormat; +import rickwporter.prettytable.OutputFormat; import rickwporter.prettytable.TableBuilder; @Command( @@ -138,6 +142,18 @@ protected int usage(String message) { return CommandLine.ExitCode.USAGE; } + public String renderJson(Object body) { + DefaultIndenter indent = new DefaultIndenter(" ", "\n"); + DefaultPrettyPrinter printer = new DefaultPrettyPrinter() + .withArrayIndenter(indent) + .withObjectIndenter(indent); + try { + return new ObjectMapper().writer(printer).writeValueAsString(body); + } catch (JsonProcessingException ex) { + throw new IllegalStateException("Could not render JSON", ex); + } + } + private String render(Object body) { if (body == null) { return ""; @@ -145,12 +161,15 @@ private String render(Object body) { if (body instanceof String || body instanceof Number || body instanceof Boolean) { return String.valueOf(body); } - PrettyTable table = new TableBuilder().build(body); + if (this.parent.format == OutputFormat.JSON) { + return this.renderJson(body); + } + + PrettyTable table = new TableBuilder().build(this.parent.format, body); if (table == null) { return ""; } - OutputFormat format = this.parent.format; - return table.formattedString(format == null ? OutputFormat.RICH : format); + return table.toString(); } protected int show(Object body) {