JSON响应为整数,但为空时为字符串

JSON响应为整数,但为空时为字符串

问题描述:

I am unmarshalling a JSON response into a struct. For one of the fields, it returns an int and a string when empty.

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

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

The response is either

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

How can I handle both an int and string response?

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

  type example struct {
 Position int`json:“ position”`
} 
  
json:无法将字符串解组到int 
  code>  pre> 
 
 

类型的Go struct字段中。响应为 p>

   {“ position”:8}或{“ position”:“ none”} 
  code>  pre> 
 
 

如何处理int和string响应? p> \ n div>

Change the type to interface{}, and then you can check the type at runtime.

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
    }
}