-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (55 loc) · 1.25 KB
/
main.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
"strings"
)
type Person struct {
Name string `json:"full_name"`
Age int `json:"-"`
Email string `json:"email,omitempty" random:"something"`
// both Faulty and DupliateFaulty will be ignored during serialization
Faulty string `json:"omitempty"`
DuplicateFaulty string `json:"omitempty"`
}
func main() {
printMarshalExample()
fmt.Println(getFieldTags(reflect.TypeOf(Person{})))
}
func printMarshalExample() {
// marshal
pp := []Person{
{
Name: "first person",
Age: 20,
Email: "first@person.com",
Faulty: "faulty",
},
{
Name: "first person",
Age: 20,
Email: "",
},
}
b, _ := json.MarshalIndent(pp, "", "\t")
fmt.Println(string(b))
// unmarshal
f, _ := os.ReadFile("person.json")
pp2 := []Person{}
_ = json.Unmarshal(f, &pp2)
fmt.Printf("%+v\n", pp2) // both "Faulty" and "DuplicateFaulty" are empty
}
func getFieldTags(t reflect.Type) map[string][]string {
if t.Kind() != reflect.Struct {
panic(fmt.Sprintf("t should be struct but is %s", t))
}
tags := make(map[string][]string)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
jTags := strings.SplitN(f.Tag.Get("json"), ",", -1)
tags[f.Name] = jTags
}
return tags
}