go编码相关01

Go编码相关

结构体标签

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
35
36
37
38
39
40
41
42
43
44
45
package main

import (
"encoding/json"
"fmt"
)

type Teacher struct {
Id int `json:"-"` //表示 在使用json编码时,这个编码不参与
Name string `json:"Teacher_name"` //表示 在使用json编码时,key会使用Teacher_name
Age int `json:"age,string"` //表示 在使用json编码时,将age转成string类型,切记中间是逗号,不能有空格
Address string `json:"address,omitempty"` //表示 在使用json编码时,如果这个字段是空值,那么忽略掉,不参与编码
gender string
}

// type Teacher struct {
// Name string
// Id int
// }

func main() {
tokey := Teacher{
Id: 1,
Name: "tokey",
Age: 20,
gender: "男"}
encodeInfo, err := json.Marshal(&tokey)
if err != nil {
fmt.Println("Marshal error,err:", err)
return
}

fmt.Println("encodeInfo string:", string(encodeInfo))

var tokey1 Teacher
err = json.Unmarshal([]byte(encodeInfo), &tokey1)
if err != nil {
fmt.Println("Unmarshal error,err:", err)
return
}
fmt.Println("tokey1:", tokey1)
}

// 1. 对于结构体进行编码(json)时:首字母必须大写,否则不参与编码
// 2. 如果json格式要求key小写,那么可以通过便签实现。
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
Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Id":1,"Name":"tokey","Age":20}
tokey1: {1 tokey 20 }

Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Name":"tokey","Age":20}
tokey1: {0 tokey 20 }

Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Teacher_name":"tokey","age":"20"}
tokey1: {0 tokey 20 }

Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Teacher_name":"tokey","age":"20"}
tokey1: {0 tokey 20 }

Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Teacher_name":"tokey","age":"20","Address":""}
tokey1: {0 tokey 20 }

Tokey@DESKTOP-7UHT0GC MINGW64 /e/GoPath/src/day05
$ go run 03-结构体标签.go
encodeInfo string: {"Teacher_name":"tokey","age":"20"}
tokey1: {0 tokey 20 }

总结

  1. 对于结构体进行编码(json)时,首字母必须大写,否则不参与编码。

  2. 如果json格式要求key小写,那么可以通过标签实现。

  3. 标签(tag)说明:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    type Teacher struct {
    //表示 在使用json编码时,这个编码不参与
    Id int `json:"-"`
    //表示 在使用json编码时,key会使用Teacher_name
    Name string `json:"Teacher_name"`
    //表示 在使用json编码时,将age转成string类型,切记中间是逗号(不能省略),不能有空格
    Age int `json:",string"`
    //表示 在使用json编码时,如果这个字段是空值,那么忽略掉,不参与编码
    Address string `json:",omitempty"`
    gender string
    }

本文标题:go编码相关01

文章作者:Tokey

发布时间:2021年07月07日 - 23:07

最后更新:2021年07月07日 - 23:07

原始链接:http://TokeyRoad.github.io/2021/07/07/go编码相关01/

许可协议: 转载请保留原文链接及作者。

0%