【问题标题】:How to unmarshal json to struct with uint8如何使用 uint8 将 json 解组为 struct
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-27
    • 2016-12-22
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    相关资源
    最近更新 更多