登录
首页 >  Golang >  Go教程

GolangJSON结构体转换技巧

时间:2026-01-14 11:51:30 307浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Golang JSON与结构体使用技巧》,聊聊,我们一起来看看吧!

Go中通过encoding/json包与结构体标签实现JSON编解码,利用json:"name"指定字段名,omitempty省略空值,"-"忽略字段,结合map[string]interface{}处理动态字段,嵌套结构体和切片应对复杂结构,实现Marshaler/Unmarshaler接口自定义时间等类型序列化,需注意导出字段首字母大写及空值判断规则。

Golang encodingJSON与结构体结合使用实践

在 Go 语言开发中,encoding/json 包与结构体的结合使用是处理 JSON 数据的核心方式。无论是解析 HTTP 请求中的 JSON 数据,还是将程序数据序列化为 JSON 响应,都离不开结构体与 json 标签的合理设计。

结构体字段与 JSON 映射

Go 中通过结构体字段的标签(tag)控制 JSON 的序列化和反序列化行为。最常见的用法是 json: 标签,用于指定字段在 JSON 中的名称。

例如:

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
    Age   int    `json:"-"`
}

说明:

  • json:"id":序列化和反序列化时,该字段对应 JSON 中的 "id" 字段。
  • omitempty:如果字段值为空(如零值、nil、空字符串等),序列化时会省略该字段。
  • json:"-":明确忽略该字段,不参与序列化或反序列化。

处理动态或未知字段

有时我们无法提前定义所有字段,比如接收第三方 API 的部分未知结构。此时可结合 map[string]interface{} 或嵌套结构体灵活处理。

示例:

type Response struct {
    Status string                 `json:"status"`
    Data   map[string]interface{} `json:"data"`
}

使用 json.Unmarshal 可将任意 JSON 对象解析到 map 中,之后按需访问字段。注意类型断言的使用:

if name, ok := data["name"].(string); ok {
    fmt.Println("Name:", name)
}

嵌套结构与切片处理

实际应用中,JSON 往往包含数组或嵌套对象。Go 结构体可通过嵌套结构体或切片自然表达。

例如:

type Address struct {
    City  string `json:"city"`
    Zip   string `json:"zip"`
}

type User struct {
    Name    string    `json:"name"`
    Emails  []string  `json:"emails"`
    Address Address   `json:"address"`
}

上述结构能正确解析如下 JSON:

{
  "name": "Alice",
  "emails": ["a@example.com", "b@example.net"],
  "address": {
    "city": "Beijing",
    "zip": "100000"
  }
}

自定义序列化行为

对于特殊类型(如时间格式、枚举值),可实现 json.MarshalerUnmarshaler 接口来自定义编解码逻辑。

常见例子是格式化时间:

type CustomTime struct {
    time.Time
}

func (ct *CustomTime) MarshalJSON() ([]byte, error) {
    return []byte(fmt.Sprintf(`"%s"`, ct.Time.Format("2006-01-02"))), nil
}

func (ct *CustomTime) UnmarshalJSON(data []byte) error {
    loc, _ := time.LoadLocation("Asia/Shanghai")
    t, err := time.ParseInLocation(`"2006-01-02"`, string(data), loc)
    if err != nil {
        return err
    }
    ct.Time = t
    return nil
}

然后在结构体中使用:

type Event struct {
    Title string      `json:"title"`
    Date  CustomTime  `json:"date"`
}

基本上就这些。合理利用结构体标签、嵌套结构和接口实现,能让 Go 程序轻松应对各种 JSON 场景。关键是结构清晰、标签准确,避免过度依赖泛型 map。不复杂但容易忽略细节,比如大小写导出和 omitempty 的触发条件。

好了,本文到此结束,带大家了解了《GolangJSON结构体转换技巧》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>