> For the complete documentation index, see [llms.txt](https://yoyo840821.gitbook.io/android-learning/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yoyo840821.gitbook.io/android-learning/gson-xu-lie-hua-fan-xu-lie-hua.md).

# GSON序列化/反序列化

## 序列化-組合的過程

假設有個class是UserInfo，要把資料組合成Json字串

```java
public class UserInfo{
    String name;
    String email;
    int age;
    
    public UserInfo(String name, String email, int age){
        this.name = name;
        this.email = email;
        this.age = age;
    }
    
}
```

```java
//1.建立物件
UserInfo userinfo = new UserInfo("Joe", "yoyo840821@icloud.com", 24);

//2. 建立gson物件
Gson gson = new Gson()
String jsonStr = gson.toJson(userinfo);

```

## 反序列化-解析的過程

有個json字串，要把它解析某個Java class

```java
String userJson = "{'age':24,'email':'yoyo840821@icloud.com','name':'Joe'}";

//1. 建立Gson物件
Gson gson = new Gson();

//2. 按照UserInfo的欄位做解析
UserInfo userinfo = gson.fromJson(userJson, UserInfo.class);
```
