File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change @@ -32,9 +32,92 @@ json.Marshal(struct {
32
32
})
33
33
```
34
34
35
+ # 临时添加额外的字段
36
+
37
+ ``` golang
38
+ type User struct {
39
+ Email string ` json:"email"`
40
+ Password string ` json:"password"`
41
+ // many more fields…
42
+ }
43
+ ```
44
+
45
+ 临时忽略掉Password字段,并且添加token字段
46
+
47
+ ``` golang
48
+ json.Marshal (struct {
49
+ *User
50
+ Token string ` json:"token"`
51
+ Password bool ` json:"password,omitempty"`
52
+ }{
53
+ User : user,
54
+ Token : token,
55
+ })
56
+ ```
57
+
35
58
# 临时粘合两个struct
59
+
60
+ ``` golang
61
+ type BlogPost struct {
62
+ URL string ` json:"url"`
63
+ Title string ` json:"title"`
64
+ }
65
+
66
+ type Analytics struct {
67
+ Visitors int ` json:"visitors"`
68
+ PageViews int ` json:"page_views"`
69
+ }
70
+
71
+ json.Marshal (struct {
72
+ *BlogPost
73
+ *Analytics
74
+ }{post, analytics})
75
+ ```
76
+
36
77
# 一个json切分成两个struct
78
+
79
+ ``` golang
80
+ json.Unmarshal ([]byte (` {
81
+ "url": "attila@attilaolah.eu",
82
+ "title": "Attila's Blog",
83
+ "visitors": 6,
84
+ "page_views": 14
85
+ }` ), &struct {
86
+ *BlogPost
87
+ *Analytics
88
+ }{&post, &analytics})
89
+ ```
90
+
37
91
# 临时改名struct的字段
92
+
93
+ ``` golang
94
+ type CacheItem struct {
95
+ Key string ` json:"key"`
96
+ MaxAge int ` json:"cacheAge"`
97
+ Value Value ` json:"cacheValue"`
98
+ }
99
+
100
+ json.Marshal (struct {
101
+ *CacheItem
102
+
103
+ // Omit bad keys
104
+ OmitMaxAge omit ` json:"cacheAge,omitempty"`
105
+ OmitValue omit ` json:"cacheValue,omitempty"`
106
+
107
+ // Add nice keys
108
+ MaxAge int ` json:"max_age"`
109
+ Value *Value ` json:"value"`
110
+ }{
111
+ CacheItem : item,
112
+
113
+ // Set the int by value:
114
+ MaxAge : item.MaxAge ,
115
+
116
+ // Set the nested struct by reference, avoid making a copy:
117
+ Value : &item.Value ,
118
+ })
119
+ ```
120
+
38
121
# 用字符串传递数字
39
122
# 容忍字符串和数字互转
40
123
# 容忍空数组作为对象
You can’t perform that action at this time.
0 commit comments