如何解组 json 以使用 uint8 进行结构化

How to unmarshal json to struct with uint8

如何将 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"`
}

我将结构 A 插入 mongo 然后我成功地做了一个 mongo 查找并打印出结构 A 对应的集合。我可以执行 bson.MarshalExtJSON 将 bson 转换为 json,然后当我执行 json.Unmarshal 将 json 转换为结构 A 时,这就是我失败的地方。

这是一个重现问题的示例 golang playground。我不明白为什么会失败?我该如何解决?

https://play.golang.org/p/0HOAxsu166j

我看到 unmarshal 使用 "float64, for JSON numbers" 但我无法使用 float64 而不是 uint8

感谢@Brits 的评论,我发现当我调用 bson.MarshalExtJSON 时我得到了 extendedJson。 json.Unmarshal() 无法像 {"$numberInt":"52"} 那样读取 extendedJson,所以这就是它失败的原因。

所以为了解决这个问题,我使用 bson.UnmarshalExtJSON() 而不是 json.Unmarshal() 来将 extendedJSON 解组到结构