</>YZIF
博客

JSON 转 Go 结构体:API 开发者的必备工具

2026-06-18

为什么需要将 JSON 转换为 Go 结构体?

在构建使用 REST API 的 Go 应用程序时,你需要结构体定义来反序列化 JSON 响应。手动将嵌套的 JSON 转换为 Go 结构体既繁琐又容易出错,而且浪费宝贵的开发时间。

实际示例:GitHub API 用户响应

以下是 GitHub API 返回的用户个人资料 JSON:

{
  "login": "octocat",
  "id": 1,
  "avatar_url": "https://github.com/images/error/octocat_happy.gif",
  "gravatar_id": "",
  "url": "https://api.github.com/users/octocat",
  "html_url": "https://github.com/octocat",
  "followers_url": "https://api.github.com/users/octocat/followers",
  "created_at": "2011-01-25T18:44:36Z",
  "updated_at": "2024-03-20T10:00:00Z",
  "plan": {
    "name": "Free",
    "space": 976562499,
    "private_repos": 10000,
    "collaborators": 0
  }
}

手动编写 Go 结构体需要这样:

type User struct {
Login string `json:"login"`
ID int `json:"id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Plan Plan `json:"plan"`
}

type Plan struct {
Name string `json:"name"`
Space int64 `json:"space"`
PrivateRepos int `json:"private_repos"`
Collaborators int `json:"collaborators"`
}

为什么使用 YZIF 的 JSON 转 Go 工具?

使用 YZIF 的 JSON 转 Go 工具,你可以:

1. **粘贴原始 JSON** — 无需清理或重新格式化 2. **即时获取结构体** — 包含正确的 json 标签、驼峰字段名和类型推断 3. **处理嵌套** — 嵌套对象自动成为嵌套结构体 4. **数组支持** — JSON 数组转换为带有正确元素类型的切片 5. **正确类型推断** — 字符串、数字、布尔值、数组、对象和时间字段都能正确识别

该工具还能处理可空字段、空数组和深度嵌套结构等边界情况。它自动将 snake_case 的 JSON 键转换为 Go 风格的驼峰字段名,并生成正确的 json 结构体标签。

Go 结构体专业建议

- 使用 `json:"fieldname,omitempty"` 跳过 JSON 输出中的零值字段
- 对于可空字段,使用指针类型(`*string`)或 `sql.NullString`
- 始终在生成的代码上运行 `go vet` 以捕获潜在问题
- 可以将多个 API 响应合并粘贴,一次性生成所有结构体

立即尝试

访问 YZIF 的 JSON 转 Go 结构体生成器,粘贴任何 JSON API 响应,几秒钟内即可获得生产就绪的 Go 结构体。