如何解码 JSON 并将其映射到 uint8 数据类型

时间:2024-03-23

浏览:365

作者:佚名

在将 JSON 解组到包含 `uint8` 数据类型的结构时,遇到错误“json: cannot unmarshal object into go struct field a.test of type uint8”。这是因为 JSON 中的数字默认使用 `float64`,而 `uint8` 是一个无符号 8 位整数。

问题内容

如何将 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 来工作


解决方案


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

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

终于介绍完啦!小伙伴们,这篇关于《如何解码 JSON 并将其映射到 uint8 数据类型》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页