Languages
[Edit]
EN

Java json pretty print (Jackson library)

4 points
Created by:
Kara
601

Quick solution:

// import com.fasterxml.jackson.databind.ObjectMapper;

new ObjectMapper()
        .writerWithDefaultPrettyPrinter() // <----- enable pretty print
        .writeValueAsString(ourObject);

Output example:

Normal json:
{"name":"john","age":23,"salary":5000,"skills":["java","js"]}

Pretty print:
{
  "name" : "john",
  "age" : 23,
  "salary" : 5000,
  "skills" : [ "java", "js" ]
}

 

Example

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

import java.io.IOException;

public class JavaJacksonPrettyPrint {

    public static void main(String[] args) throws IOException {

        String json = "{\"name\":\"john\",\"age\":23,\"salary\":5000,\"skills\":[\"java\",\"js\"]}";
        System.out.println("Normal json:");
        System.out.println(json);
        System.out.println();
        
        JsonNode rootNode = new ObjectMapper(new JsonFactory()).readTree(json);
        ObjectMapper mapper = new ObjectMapper();

        String prettyJson = mapper
                .writerWithDefaultPrettyPrinter() // <----- enable pretty print
                .writeValueAsString(rootNode);

        System.out.println("Pretty print:");
        System.out.println(prettyJson);
    }
}

Output:

Normal json:
{"name":"john","age":23,"salary":5000,"skills":["java","js"]}

Pretty print:
{
  "name" : "john",
  "age" : 23,
  "salary" : 5000,
  "skills" : [ "java", "js" ]
}

Hint: to know how to attach jackson *.jar lib to your project read this article.

Link to the library in the Maven repository:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

Alternative titles

  1. Java json beautifier
  2. java beautify json string
  3. java beautify json string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java JSON - Jackson lib

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join