**结构体序列化**
```
package main
import (
"encoding/json"
"fmt"
)
type Person struct{
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:gender`
}
func main(){
person := Person{
Name: "Tom",
Age: 18,
Gender: "男",
}
data, err := json.Marshal(person)
if err == nil{
fmt.Println(string(data)) // {"name":"Tom","age":18,"Gender":"男"}
}
}
```
**切片序列化**
```
package main
import (
"encoding/json"
"fmt"
)
func main(){
var person []map[string]interface{}
p1 := make(map[string]interface{})
p1["name"] = "Tom"
p1["age"] = 18
p1["gender"] = "男"
person = append(person, p1)
data, err := json.Marshal(person)
if err == nil{
fmt.Println(string(data)) // [{"age":18,"gender":"男","name":"Tom"}]
}
}
```
## json 反序列化
```
package main
import (
"encoding/json"
"fmt"
)
func main(){
str := "{\"name\":\"Tom\",\"age\":18,\"gender\":\"男\"}"
var person map[string]interface{}
err := json.Unmarshal([]byte(str), &person)
if err == nil {
fmt.Println(person) // map[age:18 gender:男 name:Tom]
}
}
```