如何使用 Java 中的 Gson 库对 JSON 进行漂亮打印?
一个Gson 是 Google 创建的针对 java 的 JSON 库。通过使用 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);
}
}
// Employee class
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"
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP