This post will discuss how to pretty print Json data in Kotlin.

1. Using GSON Library

To pretty-print a Json output with the Gson library, you can configure it for pretty-printing using the setPrettyPrinting() function. This is demonstrated below:

Download Code

Output:


{
  "name": "Google",
  "employees": 180000,
  "offices": [
    "Washington",
    "Virginia",
    "India"
  ]
}

 
The fromJson function deserializes the specified Json into an object of the specified class. If the class information is not available, you can use JsonParser to parse Json into a parse tree of Json elements with either the parse() or parseString() function.

Download Code

Output:


{
  "name": "Google",
  "employees": 180000,
  "offices": [
    "Washington",
    "Virginia",
    "India"
  ]
}

2. Using Jackson Library

If you prefer the Jackson library, use the writerWithDefaultPrettyPrinter() function to output Json using the pretty printer for indentation. Here’s how the code would look like:

Download Code

Output:


{
    "employees": 180000,
    "name": "Google",
    "offices": [
        "Washington",
        "Virginia",
        "India"
    ]
}

3. Using Json for Java Library

The Json for Java library provides the JsonObject.toString() function to output a pretty-printed representation of the Json object. It can be used as follows:

Download Code

Output:


{
    "employees": 180000,
    "name": "Google",
    "offices": [
        "Washington",
        "Virginia",
        "India"
    ]
}

That’s all about pretty printing Json data in Kotlin.