Friday , July 21 2017
Home / json / How to Format JSON Output PrettyPrinter Example

How to Format JSON Output PrettyPrinter Example

In this tutorials, I am going to show you how to format JSON output using PrettyPrinter Jackson.

Format JSON Output PrettyPrinter :

We can format the json string with readable format. In the previous tutorials, when we convert java Employee object to JSON, or convert Java Map to JSON string, in the both cases we got the JSON output in a single line like below:

{“studentId”:1001,”studentName”:”Rahul”,”roleNumber”:”54″,”standard”:”5th”}

If we want to format the above output like below:

{
“studentId” : “1001”,
“studentName” : “Rahul”,
“roleNumber” : “54”,
“standard” : “5th”
}

We can format the json output using writerWithDefaultPrettyPrinter() method available in ObjectMapper class.

Format JSON Output Example :


package com.onlinetutorialspoint.json;

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

public class Formate_JSON_Output {
    public static void main(String[] args) {
        Map<String,String> scoreMap = new HashMap<String,String>(); 
        scoreMap.put("Dhoni", "102");
        scoreMap.put("Yuvraj", "94");
        scoreMap.put("Raina", "82");
        scoreMap.put("Kohli", "120");
        ObjectMapper mapperObj = new ObjectMapper();
        try {
            String jsonFormat = mapperObj.writerWithDefaultPrettyPrinter().writeValueAsString(scoreMap);
            System.out.println(jsonFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}

{
“Kohli” : “120”,
“Yuvraj” : “94”,
“Dhoni” : “102”,
“Raina” : “82”
}

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

How to convert JSON to Java Object Example

Here I am going to show you how to convert JSON to Java Object using …

Leave a Reply

Your email address will not be published. Required fields are marked *