安卓如何将实体类转换为json
时间: 2024-05-12 10:20:00 浏览: 132
在Android中,可以使用Gson库将Java对象转换为JSON字符串。以下是将实体类转换为JSON的示例代码:
1. 首先,需要在build.gradle文件中添加Gson库的依赖项:
```
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
```
2. 创建一个实体类:
```
public class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
```
3. 使用Gson将实体类转换为JSON:
```
User user = new User("John", 30, "john@example.com");
Gson gson = new Gson();
String json = gson.toJson(user);
Log.d("TAG", "JSON: " + json);
```
输出结果:
```
JSON: {"name":"John","age":30,"email":"john@example.com"}
```
4. 可以将JSON字符串转换回Java对象:
```
String json = "{\"name\":\"John\",\"age\":30,\"email\":\"john@example.com\"}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
Log.d("TAG", "Name: " + user.getName() + ", Age: " + user.getAge() + ", Email: " + user.getEmail());
```
输出结果:
```
Name: John, Age: 30, Email: john@example.com
```
阅读全文