我下载了一个 JSON 文件,我不知道它的节点,但我想使用 java 来美化它。
我找到了很多解决方案,但就我而言,我不知道 JSON 文件的节点。所以请提供任何帮助
最佳答案
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 [...]
如果您愿意使用 Jackson,这里有一个可行的解决方案:
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);
上面的示例演示了如何从给定的 URL 读取 JSON 文档,这可能是也可能不是您的情况。如果它不符合您的需求,请检查ObjectMapper
API,您可以从 String
、InputStream
、File
等读取 JSON 文档。
这里的主要内容是:此解决方案不需要您了解 JSON 的结构。只要它是有效的 JSON,Jackson 就会使用其树模型来解析它。
<小时/>或者,当您似乎想要解析 Swagger/OpenAPI 2.0 JSON 文件时,您可以使用以下内容(查看 documentation 了解详细信息):
Swagger swagger = new SwaggerParser().read("https://petstore.swagger.io/v2/swagger.json");
String swaggerString = Json.pretty(swagger);
关于java - 使用java美化json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60432466/