2

For example, I want to print it as below, instead of one single line. This is a JSON string. By default, myJsonObject.toString() is a one-line String. Is there some method from org.json.JSONObject that can directly output this formatted form?

 {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }
user697911
  • 9,271
  • 20
  • 83
  • 153

2 Answers2

3

There are different ways to print pretty json string.

GSON offers a method setPrettyPrinting(),

For instance,

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement =  new JsonParser().parse(jsonString);
System.out.println(gson.toJson(jsonElement));
Kris
  • 1,498
  • 1
  • 12
  • 13
3

To indent any old JSON, just bind it as Object, like:

ObjectMapper mapper = new ObjectMapper();

Object json = mapper.readValue(myJsonObject, Object.class);

and then write it out with indentation:

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
Akash
  • 565
  • 5
  • 12