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
  • 10,043
  • 25
  • 95
  • 169

2 Answers2

4

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
  • 587
  • 5
  • 12
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,618
  • 1
  • 13
  • 13