go定义json数据
代码如下
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func main() {
//编码
user := User{Name: "zhangsan", Email: "123@qq.com", Age: 12}
jsonData, err := json.Marshal(user)
if err != nil {
fmt.Println("编码错误", err)
return
}
fmt.Println("编码后的json", string(jsonData))
//解码
jsonString := `{"name":"lisi", "email":"fd@11.cn", "age":12}`
var decodeUser User
err = json.Unmarshal([]byte(jsonString), &decodeUser)
if err != nil {
println("解码错误", err)
return
}
fmt.Printf("解码后的json %+v\n", decodeUser)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
上次更新: 2024/09/01, 20:26:32