Gson - So aktivieren Sie die hübsche JSON-Druckausgabe
In diesem Tutorial zeigen wir Ihnen, wie Sie JSON Pretty Print inGson Framework aktivieren.
1. Standardmäßig druckt Gson die JSON-Ausgabe kompakt:
GsonExample1.java
package com.example;
import com.google.gson.Gson;
public class GsonExample1 {
public static void main(String[] args) {
Gson gson = new Gson();
String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};
String json = gson.toJson(lang);
System.out.println(json);
}
}
Ausgabe
["Java","Node","Kotlin","JavaScript"]
2. Erstellen SieGson Objekt mitGsonBuilder, um JSON Pretty-Print zu aktivieren
GsonExample2.java
package com.example;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonExample2 {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};
String json = gson.toJson(lang);
System.out.println(json);
}
}
Ausgabe
[ "Java", "Node", "Kotlin", "JavaScript" ]
Note
Lesen Sie mehrGson examples