最佳答案
我试图从一个 JSON 获取一个值并将其强制转换为 int,但是它不起作用,而且我不知道如何正确地执行它。
下面是错误消息:
...cannot convert val (type interface {}) to type int: need type assertion
还有密码:
var f interface{}
err = json.Unmarshal([]byte(jsonStr), &f)
if err != nil {
utility.CreateErrorResponse(w, "Error: failed to parse JSON data.")
return
}
m := f.(map[string]interface{})
val, ok := m["area_id"]
if !ok {
utility.CreateErrorResponse(w, "Error: Area ID is missing from submitted data.")
return
}
fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64
iAreaId := int(val) // <--- Error on this line.
testName := "Area_" + iAreaId // not reaching here