小能豆

How do I get the compact/minified form of pretty-printed JSON in Java?

javascript

I need to take the pretty-printed version of JSON string and then convert it to the compact/minified form. How can it be done?

I need to convert this:

{
  "one" : "AAA",
  "two" : [ "B B", "CCC" ],
  "three" : {
    "four" : "D D",
    "five" : [ "EEE", "FFF" ]
  }
}

to this:

{"one":"AAA","two":["B B","CCC"],"three":{"four":"D D","five":["EEE","FFF"]}}

I tried to remove ‘\n’, ‘\t’, and ‘ ‘ characters; but there may be some of these characters in values so I can’t do that.

What else can be done?


阅读 72

收藏
2023-11-20

共1个答案

小能豆

To convert a pretty-printed JSON string to its compact/minified form in Java, you can use a JSON library. One common library is Jackson. Below is an example of how you can achieve this using Jackson:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonMinifier {

    public static String minifyJson(String prettyJson) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(prettyJson);
            String minifiedJson = objectMapper.writeValueAsString(jsonNode);
            return minifiedJson;
        } catch (JsonProcessingException e) {
            e.printStackTrace(); // Handle the exception appropriately
            return null;
        }
    }

    public static void main(String[] args) {
        String prettyJson = "{\n" +
                "  \"one\" : \"AAA\",\n" +
                "  \"two\" : [ \"B B\", \"CCC\" ],\n" +
                "  \"three\" : {\n" +
                "    \"four\" : \"D D\",\n" +
                "    \"five\" : [ \"EEE\", \"FFF\" ]\n" +
                "  }\n" +
                "}";

        String minifiedJson = minifyJson(prettyJson);
        System.out.println(minifiedJson);
    }
}

This example uses the Jackson library to parse the pretty-printed JSON string into a JsonNode and then converts it back to a minified JSON string using writeValueAsString. Note that this approach also ensures that the minified JSON is properly formatted and valid.

Make sure to include the Jackson library in your project. If you are using Maven, you can add the following dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.4</version> <!-- Use the latest version available -->
</dependency>

Adjust the version number according to the latest version available.

2023-11-20