Languages
[Edit]
EN

Java json pretty print (Jackson library)

1 points
Created by:
Kara
351

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

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