Format JSON with org.json

Use 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));
	}

}

result

--- 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"
}

Recommended Posts

Format JSON with org.json
Diffed with JSON
Import JSON with SolrJ
JSON validation with JSON schema
Handle JSON with minimal-json
Automate format with maven-formatter
[Java] JSON communication with jackson
Format Ruby with VS Code
[Rails] Specify format with link_to
Serializing org.joda.time.DateTime to JSON in ISO 8601 format comes with milliseconds
Convert ruby object to JSON format
Handle JSON effortlessly with Alamofire's respone Json
Create a GUI JSON Viewer with Ruby/GTK3
Output Spring Boot log in json format
Prepare the format environment with "Rails" (VScode)
Try using JSON format API in Java
Working with huge JSON in Java Lambda
Use a named format with Ruby's format method
Format the contents of LocalDate with DateTimeFormatter
Convert JSON to TSV and TSV to JSON with Ruby