Home  >  Article  >  Java  >  Pretty printing JSON in Java using Jackson library?

Pretty printing JSON in Java using Jackson library?

WBOY
WBOYforward
2023-08-20 14:25:161565browse

Pretty printing JSON in Java using Jackson library?

A Jackson API is a Java-based library that can convert Java objects to JSON and JSON to Java objects. The Jackson API is faster than other APIs, requires less memory space, and works well with large objects. We can process JSON in three different ways using Streaming API, Tree Model and Data Binding.

We can use the writerWithDefaultPrettyPrinter() method to pretty print JSON, which is a factory method of the ObjectMapper class for constructing ObjectWriter , it will use the default indentation pretty printer to serialize the object.

Grammar

public ObjectWriter writerWithDefaultPrettyPrinter()

Example

Chinese translation is:

Example

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PrettyPrintJsonJacksonTest {
   public static void main(String[] args) throws IOException {
      String data = "{\"Age\":30,\"Technologies\":            [\"Java\",\"Spark\",\"Python\"],\"Name\":\"Adithya\"}";
<strong>      </strong>ObjectMapper mapper = new ObjectMapper();
      Object json = mapper.readValue(data, Object.class);
      String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // Pretty         print JSON
      System.out.println(jsonStr);
   }
}

Output

{
 "Age" : 30,
 "Technologies" : [ "Java", "Spark", "Python" ],
 "Name" : "Adithya"
}

The above is the detailed content of Pretty printing JSON in Java using Jackson library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete