JSON 转 Go 结构体工具

将 JSON 转换为带 json tag 的 Go 结构体,并附带基于 encoding/json 的 Unmarshal 和 Marshal 辅助函数。

从 JSON 生成带 json tag 的 Go 结构体

在 Go 中,每个需要解码的 JSON 对象都要对应一个 struct,而当键名与 Go 字段名不一致时,每个字段还需要写 json tag。本工具会替你完成这些工作:allowed_origins 这样的 snake_case 键会变成 AllowedOrigins 这样的导出字段,并带上对应的 json tag;嵌套对象会生成独立的结构体类型;整数映射为 int64,小数映射为 float64。它还会基于标准库 encoding/json 生成一个 Unmarshal 函数和一个 Marshal 方法,无需任何第三方依赖。

使用方法

  1. 粘贴一段 JSON 样例,例如配置文件或 API 响应。
  2. 输入根结构体的名称,例如 ServerConfig。
  3. 将代码复制到 .go 文件中,把 package main 改成你自己的包名,然后用 json.Unmarshal 或生成的 Unmarshal 函数进行解码。

常见问题

为什么数字生成为 int64 而不是 int?
JSON 对整数大小没有限制,因此 int64 在所有平台上都是安全的选择。如果你清楚取值范围,复制后可以把字段改为 int。
如何在 json tag 中添加 omitempty?
生成器只会写出与样例键名对应的普通 tag。对于希望在 Marshal 时为空就省略的字段,请手动加上 ,omitempty;它不会影响解码行为。
可为 null 或缺失的字段如何处理?
如果样例中某个字段为 null,或在部分数组元素中缺失,它会被生成为 *string 这样的指针类型,这样你就能区分值不存在和值为空。

示例:JSON 转 Go

输入 JSON

{
  "host": "0.0.0.0",
  "port": 8080,
  "debug": false,
  "allowed_origins": ["https://jsonkit.org"],
  "database": { "dsn": "postgres://localhost/app", "max_conns": 20 }
}

生成的 Go 代码(ServerConfig)

// Code generated from JSON Schema using quicktype. DO NOT EDIT.
// To parse and unparse this JSON data, add this code to your project and do:
//
//    serverConfig, err := UnmarshalServerConfig(bytes)
//    bytes, err = serverConfig.Marshal()

package main

import "encoding/json"

func UnmarshalServerConfig(data []byte) (ServerConfig, error) {
	var r ServerConfig
	err := json.Unmarshal(data, &r)
	return r, err
}

func (r *ServerConfig) Marshal() ([]byte, error) {
	return json.Marshal(r)
}

type ServerConfig struct {
	Host           string   `json:"host"`
	Port           int64    `json:"port"`
	Debug          bool     `json:"debug"`
	AllowedOrigins []string `json:"allowed_origins"`
	Database       Database `json:"database"`
}

type Database struct {
	DSN      string `json:"dsn"`
	MaxConns int64  `json:"max_conns"`
}

将 JSON 转换为其他语言