Utilisez org.json.JSONObject.toString (int indentFactor).
package hello.json;
import org.json.JSONArray;
import org.json.JSONObject;
public class HelloOrgJson {
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("key1", "value1");
json.put("key2", "value2");
String[] ss = { "a", "b", "c" };
JSONArray arr = new JSONArray();
for (String s : ss) {
JSONObject o = new JSONObject();
o.put("xx", s);
arr.put(o);
}
json.put("arr", arr);
System.err.println("--- no formatting ---");
System.err.println(json.toString());
System.err.println("--- pretty printed ---");
System.err.println(json.toString(1));
}
}
résultat
--- no formatting ---
{"key1":"value1","arr":[{"xx":"a"},{"xx":"b"},{"xx":"c"}],"key2":"value2"}
--- pretty printed ---
{
"key1": "value1",
"arr": [
{"xx": "a"},
{"xx": "b"},
{"xx": "c"}
],
"key2": "value2"
}