Golang JSON解码器未按预期工作的问题如何解决
Golang JSON解码器未按预期工作的问题如何解决 请考虑以下代码:
package main
import (
"fmt"
"encoding/json"
"bytes"
)
func main() {
j := []byte("{\"bandwidth\":5120}")
type M struct {
rate float64 `json:"bandwidth"`
}
r := M{}
decoder := json.NewDecoder(bytes.NewReader(j))
err := decoder.Decode(&r)
fmt.Printf("%+v %+v", r, err)
}
它返回 {rate:0} <nil>,这是什么问题?
更多关于Golang JSON解码器未按预期工作的问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
4 回复
只需将结构体改为
type M struct {
Bandwidth float64 `json:"bandwidth"`
}
更多关于Golang JSON解码器未按预期工作的问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
JSON解码器仅适用于公共字段。你需要将其设为Rate。另外,我不确定它是否适用于函数内的局部类型,或者这些类型是否需要位于包级别。
// 代码示例保留原样
函数局部类型工作得很好。当我只需要在函数中使用结构体时,就会使用它们。
问题在于结构体字段 rate 未导出(小写开头),导致 JSON 解码器无法访问该字段进行赋值。在 Go 中,只有导出的字段(首字母大写)才能被 encoding/json 包处理。
以下是修正后的代码:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
j := []byte("{\"bandwidth\":5120}")
type M struct {
Rate float64 `json:"bandwidth"` // 字段改为首字母大写
}
r := M{}
decoder := json.NewDecoder(bytes.NewReader(j))
err := decoder.Decode(&r)
fmt.Printf("%+v %+v", r, err) // 输出: {Rate:5120} <nil>
}
关键修改:
- 将结构体字段从
rate改为Rate(首字母大写) - 保持 JSON 标签
json:"bandwidth"不变,确保正确映射 JSON 字段
现在解码器能正确将 JSON 中的 bandwidth 值(5120)赋给结构体的 Rate 字段。

