【发布时间】:2020-01-29 01:42:04
【问题描述】:
如何将 json 解组为包含 uint8 的结构?我收到错误消息json: cannot unmarshal object into Go struct field A.test of type uint8
在我的结构中,我有
type A struct {
Test uint8 `json:"test omitempty" bson:"test"`
}
我将 struct A 插入到 mongo 中,然后我成功地做了一个 mongo 查找并打印出 struct A 对应的集合。我可以执行 bson.MarshalExtJSON 将 bson 转换为 json,然后当我执行 json.Unmarshal 将 json 转换为 struct A 时,这就是我失败的地方。
这是一个重现问题的示例 golang Playground。我不明白为什么这会失败?我该如何解决?
https://play.golang.org/p/0HOAxsu166j
我看到 unmarshal 使用“float64,用于 JSON 数字”,但我也无法使用 float64 而不是 uint8
【问题讨论】:
-
将 JSON 解组为 int8 works fine 但您似乎正在尝试使用 JSON 解析器解组 BSON 字符串?
-
好的,问题是我有extendedJson而不是纯JSON?我不认为称它为 BSON 字符串是准确的
-
对不起,你是对的(只是注意到它不是普通的旧 JSON,你使用了 BSON 包)它的扩展 JSON,这意味着你正在尝试将对象
{"$numberInt":"52"}解码为 uint8。 -
显然相关,基于此
$numberInt事物:stackoverflow.com/q/30703171/1256452
标签: json go struct unmarshalling