I have a JSON file that I downloaded and I don't know its nodes but I want to beautify it using java.
I found many solutions but in my case, I don't know the nodes of my JSON file. So any help please
I have a JSON file that I downloaded and I don't know its nodes but I want to beautify it using java.
I found many solutions but in my case, I don't know the nodes of my JSON file. So any help please
I swear I tried all the solutions mentioned above but the problem that in order to build a JSON well-formed file using java (Jackson, Gson, json ...) you need to know the nodes of your file but I don't [...]
If you are open to use Jackson, here's a solution that will work:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
JsonNode jsonNode = mapper.readTree(new URL("https://petstore.swagger.io/v2/swagger.json"));
String formattedJson = mapper.writeValueAsString(jsonNode);
The example above demonstrates how to read a JSON document from a given URL, which may or may not be your case. If it doesn't suit your needs, check the ObjectMapper
API, as you can read JSON documents from a String
, from an InputStream
, from a File
and others.
The main thing here is: This solution doesn't require you to know the structure of the JSON. As long it's a valid JSON, Jackson will use its tree model to parse it.
Alternatively, as you seem to want to parse a Swagger/OpenAPI 2.0 JSON file, you can use the following (check the documentation for details):
Swagger swagger = new SwaggerParser().read("https://petstore.swagger.io/v2/swagger.json");
String swaggerString = Json.pretty(swagger);