要在安卓项目中使用Gson库,可以按照以下步骤进行操作:
dependencies {
implementation 'com.google.code.gson:gson:2.8.7'
}
public class Person {
private String name;
private int age;
// 构造函数、Getter和Setter方法等
}
将对象转换为JSON字符串:
Person person = new Person("Alice", 25);
Gson gson = new Gson();
String json = gson.toJson(person);
将JSON字符串转换为对象:
String json = "{\"name\":\"Bob\",\"age\":30}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
注意:在进行反序列化时,需要确保JSON字符串的键与Java类的属性名称相匹配。
这样,你就可以在安卓项目中使用Gson库进行JSON序列化和反序列化了。