如何使用Java中的Gson库漂亮地打印JSON?
一个GSON 是一个JSON库Java,它是由谷歌创建的。通过使用Gson,我们可以生成JSON 并将JSON转换为Java对象。默认情况下,Gson可以以紧凑格式打印JSON。要启用Gson漂亮打印,我们必须使用GsonBuilder 类的setPrettyPrinting()方法配置Gson实例,并且此方法将Gson配置为输出适合页面漂亮打印的JSON。
语法
public GsonBuilder setPrettyPrinting()
示例
import java.util.*; import com.google.gson.*; public class PrettyJSONTest { public static void main( String[] args ) { Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print String prettyJson = gson.toJson(emp); System.out.println(prettyJson); } } //员工阶层 class Employee { private String name, id, designation, technology, location; public Employee(String name, String id, String designation, String technology, String location) { super(); this.name = name; this.id = id; this.designation = designation; this.technology = technology; this.location = location; } public String getName() { return name; } public String getId() { return id; } public String getDesignation() { return designation; } public String getTechnology() { return technology; } public String getLocation() { return location; } }
输出结果
{ "name": "Raja", "id": "115", "designation": "Content Engineer", "technology": "Java", "location": "Hyderabad" }