Auto Light Dark
Auto Light Dark
German English

toJson

Code

String toJson(Object object)
String toJson(Object object, boolean prettyPrint)

Beschreibung

Konvertiert das übergebene Objekt in einen JSON-String.

Parameter

  • object (Object) - Das zu konvertierende Objekt.

  • prettyPrint (boolean) - [optional] true Um einen formatierten String zu erhalten
    false Um einen kompakten String zu erhalten (Standardwert)

Rückgabe

String - Das Objekt als ein JSON-String.

Beispiele

String jsonPerson = JsonUtils.toJson(new Person("Carmen", 42));

Map<String, String> cont1 = new LinkedHashMap<>();
cont1.put("keyCont1", "valCont1");
cont1.put("keyCont2", "valCont2");
Map<String, String> cont2 = new LinkedHashMap<>();
cont2.put("keyCont21", "valCont21");
cont2.put("keyCont22", "valCont22");
Map<String, Object> test = new LinkedHashMap<>();
test.put("key1", "val1");
test.put("key2", "val2");
test.put("key3", cont1);
test.put("key4", cont2);

String compactExpected = "{\"key1\":\"val1\",\"key2\":\"val2\"," +
  "\"key3\":{\"keyCont1\":\"valCont1\",\"keyCont2\":\"valCont2\"}," +
  "\"key4\":{\"keyCont21\":\"valCont21\",\"keyCont22\":\"valCont22\"}}";
Assertions.assertEquals(compactExpected, JsonUtils.toJson(test), "Test1 compact");

// the pretty output ends lines with CRLF
String prettyExpected = """\
{
\t"key1": "val1",
\t"key2": "val2",
\t"key3": {
\t\t"keyCont1": "valCont1",
\t\t"keyCont2": "valCont2"
\t},
\t"key4": {
\t\t"keyCont21": "valCont21",
\t\t"keyCont22": "valCont22"
\t}
}
""";
Assertions.assertEquals(prettyExpected, JsonUtils.toJson(test, true).normalize(), "Test2 pretty");