📅  最后修改于: 2023-12-03 15:01:05.199000             🧑  作者: Mango
Gson是一个Java库,用于将Java对象序列化为JSON格式,或将JSON格式反序列化为Java对象。Gson通过提供简单易用的API,使得处理JSON数据变得容易。
在使用Gson之前,需要先将Gson库加入到项目中。
在项目的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
手动从https://github.com/google/gson/releases下载最新版的Gson,然后将jar文件添加到项目的classpath中。
将Java对象序列化为JSON格式,可以使用Gson的toJson()
方法。toJson()
方法接收一个Java对象,然后返回一个JSON格式的字符串。
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
User user = new User("Jack", "Smith", 25, "jack.smith@gmail.com", new String[]{"Java", "Python", "Ruby"});
String json = gson.toJson(user);
System.out.println(json);
}
}
class User {
private String firstName;
private String lastName;
private int age;
private String email;
private String[] programmingLanguages;
public User(String firstName, String lastName, int age, String email, String[] programmingLanguages) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
this.programmingLanguages = programmingLanguages;
}
}
输出结果:
{
"firstName": "Jack",
"lastName": "Smith",
"age": 25,
"email": "jack.smith@gmail.com",
"programmingLanguages": [
"Java",
"Python",
"Ruby"
]
}
将JSON格式反序列化为Java对象,可以使用Gson的fromJson()
方法。fromJson()
方法接收一个JSON格式的字符串和一个Class对象作为参数,然后返回一个对应的Java对象。
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{\"firstName\":\"Jack\",\"lastName\":\"Smith\",\"age\":25,\"email\":\"jack.smith@gmail.com\",\"programmingLanguages\":[\"Java\",\"Python\",\"Ruby\"]}";
User user = gson.fromJson(json, User.class);
System.out.println(user.getFirstName());
}
}
class User {
private String firstName;
private String lastName;
private int age;
private String email;
private String[] programmingLanguages;
public User(String firstName, String lastName, int age, String email, String[] programmingLanguages) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
this.programmingLanguages = programmingLanguages;
}
public String getFirstName() {
return firstName;
}
}
输出结果:
Jack
有时候,我们需要处理一些不确定格式的JSON数据。Gson提供了JsonElement
类来处理未知JSON格式的数据。JsonElement
支持以下类型:
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
String json1 = "{\"firstName\":\"Jack\",\"lastName\":\"Smith\",\"age\":25,\"email\":\"jack.smith@gmail.com\",\"programmingLanguages\":[\"Java\",\"Python\",\"Ruby\"]}";
String json2 = "{\"id\":1,\"name\":\"Apple\",\"price\":2.5}";
JsonObject jsonObject1 = gson.fromJson(json1, JsonObject.class);
JsonObject jsonObject2 = gson.fromJson(json2, JsonObject.class);
System.out.println("jsonObject1");
System.out.println(jsonObject1.getAsJsonPrimitive("firstName").getAsString());
System.out.println(jsonObject1.getAsJsonPrimitive("lastName").getAsString());
System.out.println(jsonObject1.getAsJsonPrimitive("age").getAsInt());
System.out.println(jsonObject1.getAsJsonPrimitive("email").getAsString());
System.out.println(jsonObject1.getAsJsonArray("programmingLanguages").get(0).getAsString());
System.out.println(jsonObject1.getAsJsonArray("programmingLanguages").get(1).getAsString());
System.out.println(jsonObject1.getAsJsonArray("programmingLanguages").get(2).getAsString());
System.out.println("jsonObject2");
System.out.println(jsonObject2.getAsJsonPrimitive("id").getAsInt());
System.out.println(jsonObject2.getAsJsonPrimitive("name").getAsString());
System.out.println(jsonObject2.getAsJsonPrimitive("price").getAsFloat());
}
}
输出结果:
jsonObject1
Jack
Smith
25
jack.smith@gmail.com
Java
Python
Ruby
jsonObject2
1
Apple
2.5
有时候,我们需要自定义序列化和反序列化的行为,Gson提供了JsonSerializer
和JsonDeserializer
两个接口,可以实现自定义序列化和反序列化逻辑。
import com.google.gson.*;
import java.lang.reflect.Type;
public class GsonExample {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(User.class, new UserAdapter());
Gson gson = builder.create();
String json = "{\"name\":\"Jack\",\"age\":\"25\"}";
User user = gson.fromJson(json, User.class);
System.out.println(user.getName());
}
}
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
}
class UserAdapter implements JsonSerializer<User>, JsonDeserializer<User> {
@Override
public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String name = jsonObject.get("name").getAsString();
String age = jsonObject.get("age").getAsString();
return new User(name, Integer.parseInt(age));
}
@Override
public JsonElement serialize(User user, Type typeOfT, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user.getName());
jsonObject.addProperty("age", user.getAge());
return jsonObject;
}
private int getAge() {
return age;
}
}
输出结果:
Jack