当我对REST API进行HTTP调用时,我可能会将JSON值count作为数字或字符串返回.在任何一种情况下,我都想把它整理成一个整数.我怎么能在Go中处理这个?
使用"string"字段标记选项指定应将字符串转换为数字.该选项的 文档是:
"string"选项表示字段在JSON编码的字符串中存储为JSON.它仅适用于字符串,浮点,整数或布尔类型的字段.在与JavaScript程序通信时,有时会使用这种额外的编码级别:
这是一个使用示例:
type S struct {
Count int `json:"count,string"`
}
Run Code Online (Sandbox Code Playgroud)
如果JSON值可以是数字或字符串,则解组为接口{}并在解组后转换为int:
Count interface{} `json:"count,string"`
Run Code Online (Sandbox Code Playgroud)
使用此函数将interface {}值转换为int:
func getInt(v interface{}) (int, error) {
switch v := v.(type) {
case float64:
return int(v), nil
case string:
c, err := strconv.Atoi(v)
if err != nil {
return 0, err
}
default:
return 0, fmt.Errorf("conversion to int from %T not supported", v)
}
}
Run Code Online (Sandbox Code Playgroud)