[JAVA] Formatieren Sie JSON mit org.json

Verwenden Sie 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));
	}

}

Ergebnis

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

Formatieren Sie JSON mit org.json
Anders als bei JSON
Importieren Sie JSON mit SolrJ
Validierung von JSON mit JSON-Schema
Behandeln Sie JSON mit minimal-json
Automatisieren Sie das Format mit dem Maven-Formatierer
[Java] JSON-Kommunikation mit Jackson
Formatieren Sie Ruby mit VS-Code
[Rails] Geben Sie das Format mit link_to an
Die Serialisierung von org.joda.time.DateTime zu JSON im ISO8601-Format erfolgt in Millisekunden
Konvertieren Sie das Ruby-Objekt in das JSON-Format
Behandeln Sie JSON mühelos mit Alamofires Antwort Json
Spring Boot-Protokoll im JSON-Format ausgeben
Bereiten Sie die Formatumgebung für "Rails" (VScode) vor.
Versuchen Sie es mit der JSON-Format-API in Java
Behandeln Sie große JSON mit Java Lambda
Verwenden Sie das benannte Format mit Rubys Formatmethode
Formatieren Sie den Inhalt von LocalDate mit DateTimeFormatter
Konvertieren Sie mit Ruby von JSON nach TSV und von TSV nach JSON