JSON 转 Go struct 思路
JSON Schema 是语言无关的中间表示。拿到 Schema 后,按 Go 的类型规则映射一遍,就能得到 struct。
类型映射表
| JSON Schema | Go 类型 |
|---|---|
| string | string |
| integer | int64 |
| number | float64 |
| boolean | bool |
| object | struct { … } |
| array | []T(T 为元素类型) |
| null | *T 或 interface{} |
示例
Schema(来自工具生成):
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"tags": { "type": "array", "items": { "type": "string" } }
},
"required": ["name", "age", "tags"]
}
对应 Go struct:
type User struct {
Name string `json:"name"`
Age int64 `json:"age"`
Tags []string `json:"tags"`
}
注意
- 整数 vs 浮点:接口返回
1.0还是1决定用int64还是float64。 - 可空字段用指针(
*string)更稳妥。 - 字段名用 json tag 对齐,Go 里用大写导出。