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

后端 未结 4 1925
孤城傲影
孤城傲影 2020-12-10 01:08

How do I make Jackson's build() method pretty-print its JSON output? Here is an example that pretty-prints the ugly form of JSON code. I need to take the nice version of

4条回答
  •  无人及你
    2020-12-10 01:49

    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());
    

提交回复
热议问题