JSON响应为int,但为空时为字符串

时间:2017-11-22 13:04:24

标签: go

我正在将JSON响应解组为struct。对于其中一个字段,它在空时返回一个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和字符串响应?

1 个答案:

答案 0 :(得分:0)

将类型更改为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
    }
}