【问题标题】:JSON response is int but string when emptyJSON响应为int但为空时为字符串
【发布时间】:2017-11-23 21:39:21
【问题描述】:

我正在将 JSON 响应解组为一个结构。对于其中一个字段,它在为空时返回一个 int 和一个字符串。

type example struct {    
  Position int `json:"position"`
}

json: cannot unmarshal string into Go struct field .position of type int

响应是

{"position":8} or {"position":"none"}

如何同时处理 int 和 string 响应?

【问题讨论】:

  • golang.org/pkg/encoding/json/#Number 提示:请务必阅读整个软件包文档。
  • 如果 JSON 中的 position 字段始终位于双引号内(如 "18"),则只需将标签更改为 json:"position,string"。否则你必须实现 UnmarshalJSON 方法。
  • 谢谢大家!我会研究这些选项
  • @KavehShahbazian 是的,它是双引号,添加您的建议时仍然收到消息
  • @1mmerse 我错了。我没有足够注意另一个值是"none" 而不是""。这只能通过编写UnmarshalJSON 方法来实现。

标签: go


【解决方案1】:

将类型改为interface{},然后就可以在运行时查看类型了。

type example struct {    
    Position interface{} `json:"position"`
}
/*
Returns an int and a bool, indicating if a position exists.
*/
func (e * example) getValue() (int,bool){
    if v,ok := Position.(int) {
      return v,true
    } else {
     return 0,false
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-16
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多