把 JSON 转换成带有 encoding/json 标签的 Go struct 定义。字段名遵循 Go 的导出命名规则和 golint 的缩写词列表(ID、URL、API 等),各列也像经过 gofmt 一样对齐。
当你需要一个类型来 json.Unmarshal webhook payload 或 API 响应,需要 net/http、Gin 或 Echo 处理函数的请求体 struct,或者 CLI 的配置 struct 时,它都很有用。
omitempty 标签。结构体名 中输入顶层 struct 的名称(默认 Root);它会以 ?name= 的形式保留在 URL 中。.go 文件中并加上 package 子句。如果发现了时间字段,会包含 import "time"。var ev WebhookEvent; err := json.Unmarshal(body, &ev) 的方式使用。{
"event_id": "evt_1Pq",
"type": "invoice.paid",
"created_at": "2024-05-01T03:15:00Z",
"amount_cents": 4999,
"customer": { "id": "cus_9", "email": "kim@example.com" },
"retry_count": null
}import "time"
type WebhookEvent struct {
EventID string `json:"event_id"`
Type string `json:"type"`
CreatedAt time.Time `json:"created_at"`
AmountCents int `json:"amount_cents"`
Customer Customer `json:"customer"`
RetryCount any `json:"retry_count,omitempty"`
}
type Customer struct {
ID string `json:"id"`
Email string `json:"email"`
}
按照 golint 的缩写词规则,event_id 变成 EventID;RFC 3339 字符串 created_at 被推断为 time.Time,因此添加了 import "time"。retry_count 是 null,类型未知,于是变成带 omitempty 的 any。
json:"originalKey" 标签,在部分行中缺失或包含 null 的字段还会加上 ,omitempty。int、string、bool、struct、time.Time)变成指针(*int),以区分“不存在”和零值。slice 和 any 本身就可以为 nil,保持非指针。int,超出则为 int64,出现小数时为 float64。2024-05-01T03:15:00Z 这样的 RFC 3339 字符串会被推断为 time.Time。user_id → UserID,home_url → HomeURL);以数字开头的 key 会加上 Field 前缀。"" 这类无法出现在 Go json 标签中的 key 会被跳过,并在 struct 上方的注释中列出。[]Root 的注释。根据支付或 Git 托管服务发来的示例事件生成 struct,用 json.NewDecoder(r.Body).Decode(&ev) 解码,而不必对 map[string]any 反复做类型断言。
根据客户端的请求示例生成 c.ShouldBindJSON(&req) 所用的 struct,再在需要的地方加上 binding:"required" 标签。
把 config.json 转成 struct 一次,之后在 os.ReadFile 后调用一次 json.Unmarshal,就能以类型化的值拿到全部配置。
time.Time;2024-05-01 03:15:00 这样的值或 Unix 时间戳仍是 string 或 int。json.Unmarshal 默认忽略未知 key,并且不区分大小写地匹配 key。需要严格解码时请使用 Decoder.DisallowUnknownFields()。int 是 64 位的,但只有示例值超过 32 位时才会写成 int64。对于可能增长的 ID,自行改成 int64 更安全。null 的值会变成 any;知道真实类型后请替换。*int 这样的指针?普通的 int 字段在 key 缺失时为 0,与真正的 0 无法区分。指针在 key 不存在或为 null 时是 nil,再配合 omitempty,重新 marshal 时就会省略该 key。
encoding/json 只读写导出的(首字母大写的)字段;小写字段即使有标签也会被忽略。在 Go 中,名称保持大写,JSON key 写在标签里。
retry_count 这样的 null 字段输出成了 any。示例中只有 null,没有可以推断类型的依据。把另一份带有真实值的响应一起放进数组再转换,或者手动改成 *int 之类的类型。
能。把 struct 粘贴到顶部的 Go struct → JSON 标签页,它会读取标签并生成示例 JSON。