← 中文资源

简体中文版本

JSON 反序列化到结构体

用 json tags 把 JSON 对象解码进结构体:缺失字段保持零值不做任何猜测,类型不匹配当场显式报错而不是静默塞入空值。port 传字符串 "not-a-number" 时 Unquote 立即失败,fmt 打印 bad type error 为 true。

阅读英文原文

实现说明

JSON 反序列化到结构体的核心是函数 main。 err 在 1 个调用点被检查,之后才会使用其他结果。

使用要点

  • 演示输出是带标签的(decode failed:、bad type error:),每个操作都会留下自己的一行标注。

常见问题

运行「JSON 反序列化到结构体」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 decode failed:、bad type error: 标签标明各步骤。

核心语句

payload := `{"host": "api.devexamples.com", "port": 443}`

代码示例

package main

import (
	"encoding/json"
	"fmt"
)

type Server struct {
	Host    string  `json:"host"`
	Port    int     `json:"port"`
	TLSEnabled bool `json:"tls"`
}

func main() {
	payload := `{"host": "api.devexamples.com", "port": 443}`

	var s Server
	if err := json.Unmarshal([]byte(payload), &s); err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	// 缺失字段保持零值,不做隐式猜测
	fmt.Printf("%s:%d tls=%v\n", s.Host, s.Port, s.TLSEnabled)

	// 类型不匹配立刻报错,而不是静默塞进零值
	bad := `{"host": "h", "port": "not-a-number"}`
	err := json.Unmarshal([]byte(bad), &s)
	fmt.Println("bad type error:", err != nil)
}