Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the compact form of pretty-printed JSON code?

Tags:

java

json

minify

How do I make Jackson's build() method pretty-print its JSON output? is an example that pretty-prints the JSON string.

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?

like image 788
mtyurt Avatar asked Aug 29 '12 08:08

mtyurt


2 Answers

Jackson allows you to read from a JSON string, so read the pretty-printed string back into Jackson and then output it again with pretty-print disabled.

See converting a String to JSON

Simple Example

    String prettyJsonString = "{ \"Hello\" : \"world\"}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readValue(prettyJsonString, JsonNode.class);
    System.out.println(jsonNode.toString());

Requires

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>
like image 78
Brad Avatar answered Oct 20 '22 09:10

Brad


With the streaming API, you can use JsonGenerator.copyCurrentEvent() to easily re-output the token stream with whatever pretty-printing applied you want, including the default of no whitespace; this avoids buffering the entire document in memory and building a tree for the document.

// source and out can be streams, readers/writers, etc.
String source = "   { \"hello\" : \" world \"  }  ";
StringWriter out = new StringWriter();

JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(source);
try (JsonGenerator gen = factory.createGenerator(out)) {
    while (parser.nextToken() != null) {
        gen.copyCurrentEvent(parser);
    }
}

System.out.println(out.getBuffer().toString()); // {"hello":" world "}

You can use the same approach to pretty-print a JSON document in a streaming fashion:

// reindent
gen.setPrettyPrinter(new DefaultPrettyPrinter());
like image 7
Miles Avatar answered Oct 20 '22 11:10

Miles