如何使用uint8解组json以构建结构

问题描述 投票:0回答:1

您如何将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游乐场。我不明白为什么这会失败?我该如何解决?

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

[我看到unmarshal使用“ float64,表示JSON数字”,但我也无法使用float64而不是uint8来工作

json go struct unmarshalling
1个回答
0
投票

由于@Brits的评论,我发现当我调用bson.MarshalExtJSON时,我得到了ExtendedJson。 json.Unmarshal()无法读取诸如{"$numberInt":"52"}的extendedJson,因此这就是失败的原因。

因此,为了解决它,我正在使用bson.UnmarshalExtJSON()而不是json.Unmarshal()以便能够将extendedJSON编组到结构中

© www.soinside.com 2019 - 2024. All rights reserved.