当我对 REST API 进行 HTTP 调用时,我可能会以数字或字符串形式返回 JSON 值 count
。在任何一种情况下,我都想将其编码为整数。我该如何在 Go 中处理这个问题?
最佳答案
使用“string”字段标签选项指定应将字符串转换为数字。 documentation选项是:
The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:
这是一个使用示例:
type S struct {
Count int `json:"count,string"`
}
如果 JSON 值可以是数字或字符串,则解码为 interface{} 并在解码后转换为 int:
Count interface{} `json:"count,string"`
使用此函数将 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
}
return c, nil
default:
return 0, fmt.Errorf("conversion to int from %T not supported", v)
}
}
关于json - 解码 JSON 值,可以是字符串或数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687271/