json.Unmarshal返回nil错误但数据为空,根本原因是字段未导出或json标签不匹配;需确保首字母大写、标签一致,并用*string等处理null,用json.RawMessage或interface{}应对类型不一致,用json.Encoder.SetEscapeHTML(false)避免中文转义。
常见现象是 json.Unmarshal 返回 nil,但结构体字段全是零值(0、""、nil),实际 JSON 数据明明有内容。根本原因通常是字段未导出(首字母小写)或标签不匹配。
encoding/json 只能序列化/反序列化**导出字段**(首字母大写)"user_name",而结构体字段是 UserName string,必须加 json:"user_name" 标签,否则无法映射null 值,对应字段类型不能是基础类型(如 string),需改用指针(*string)或 sql.NullString 类型type User struct {
ID int `json:"id"`
UserName string `json:"user_name"` // 必须显式声明,否则忽略
Email *string `json:"email"` // 支持 null
}
API 返回字段不稳定(比如某次返回 "age": 25,另一次是 "age": "25"),直接绑定到 int 会 panic。不能依赖“数据一定规范”,得做防御性解析。
json.RawMessage 延迟解析:先解到一个中间字段,再按需转成 int、string 或其他类型interface{},再用类型断言 + fmt.Sprintf 或 strconv 转换Unmarshal 时直接绑定到强类型字段,尤其来自第三方 API 的响应type Response struct {
Data json.RawMessage `json:"data"`
}
// 后续:json.Unmarshal(data, &target) 或 json.Unmarshal(data, &strVal)
默认 json.Marshal 会将非 ASCII 字符(如中文)转义为 Unicode 码点,结果像 "\u4f60\u597d"。这不是错误,而是标准行为;但日志、调试或前端直读时体验差。
json.MarshalIndent 不解决转义问题
json.Encoder 并调用其 SetEscapeHTML(false) 方法(注意:该方法实际也禁用 Unicode 转义)var buf bytes.Buffer enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) // 关键:禁用 Unicode 和 HTML 转义 enc.Encode(user)
例如外层 JSON 有 "profile": {"name": "Alice"},但 Profile 字段类型写成 Profile string(而非 Profile struct{...}),Unmarshal 仍返回 nil 错误,只是静默跳过该字段。
json.Decoder 替代 json.Unmarshal,并设置 DisallowUnknownFields() 捕获多余字段,间接暴露结构偏差dec := json.NewDecoder(strings.NewReader(jsonStr)) dec.DisallowUnknownFields() // 遇到 struct 中没有定义的 key 就报错 err := dec.Decode(&user)关键点在于:Go 的 JSON 包设计偏“宽容”,不报错不等于数据正确;真正容易被忽略的是字段导出性、标签一致性、以及嵌套层级的类型精确匹配——这些地方一错,数据就丢得无声无息。
来电咨询