---
# System prepended metadata

title: Google Gson
tags: [Java]

---

[toc]

# JSON
Javascript Object Notation (/'dʒeɪsən/) 是一種資料交換格式。
(Data Interchange Format)
    
(RFC 8259)
    
JSON中的各種資料類型:
```
array   //[data1,data2,data3...]
string  //"a string"
number  //1, 0, -1.5 ...
boolean //true, false
null
object  //無序的 ``key: value`` pairs, {"k1": v1,"k2": v2...}
```

JSON檔以json為副檔名。

JSON document本身為一個object組成

JSON 不存在註解
    
範例:
```json=
{ 
  "name": "andy",
  "age": 19,
  "email": "contact@speedcubing.top",
  "properties": {
     "birthday": "2001-09-11",
     "city": "Taipei"
  }
}
```
# Gson
maven: com.google.code.gson
source: https://github.com/google/gson

Gson是一個Java的Library, 
 
### 用途
- 把物件轉成JSON String。 (Serialization)
- 把JSON String轉成一個物件。 (Unserialization)
- 解析JSON
- ...
    
(皆無須更動原物件程式碼)

### Example
假設有個物件User
```java=
class User {
    public String name;
    public int age;
    public String email;

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
}
```
### 把物件轉成JSON String
```java=
User user = new User("Andy",19,"contact@speedcubing.top");

Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
```
輸出結果:
```{"name":"andy","age":19,"email":"contact@speedcubing.top"}```
### 把JSON String轉成一個物件
```java=
String json = "{\"name\":\"Kevin\",\"age\":23,\"email\":\"kevin@idontknow.com\"}";
Gson gson = new Gson();
        
User user = gson.fromJson(json, User.class);
System.out.println("Name: " + user.name);
System.out.println("Age: " + user.age);
System.out.println("Email: " + user.email);
```
輸出結果:
```
Name: Kevin
Age: 23
Email: kevin@idontknow.com
```
### 解析JSON
可以解析一個JSON String, 或是一個Reader(IO)
    
常用物件:
JsonElement: 各種資料類型的父類, 有getAsString, getAsInt, getAsJsonObject..等等方法
JsonObject: 有JsonElemet get(String key)方法,可以取值

    
假設以下內容存於test.json
```json=
{ 
  "name": "andy",
  "age": 19,
  "email": "contact@speedcubing.top",
  "properties": {
     "birthday": "2001-09-11",
     "city": "Taipei"
  }
}
```
從Reader test.json解析JSON內容
```java=
FileReader reader = new FileReader("test.json");
JsonElement e = JsonParser.parseReader(reader);
JsonObject object = e.getAsJsonObject();

String name = object.get("name").getAsString();
System.out.println(name);

JsonObject properties = object.get("properties").getAsJsonObject();

System.out.println(properties);
System.out.println(properties.get("city").getAsString());
```
題外話: 把上面的程式用Python寫:
~~Java真該死~~
```python=
import json

with open("test.json", "r") as file:
    data = json.load(file)

name = data["name"]
print(name)

properties = data["properties"]

print(properties)
print(properties["city"])
```
