Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

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

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 JSON code then convet it to ugly fom. How can it be done? I need to convert this:

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

to this:

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

I tried to remove ' ', '', and ' ' characters; but there may be some of these characters in values so I can't do that. What else can be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...