相关疑难解决方法(0)

将interface {}转换为int

我正在尝试从JSON获取一个值并将其转换为int但它不起作用,我不知道如何正确地执行它.

这是错误消息:

...cannot convert val (type interface {}) to type int: need type assertion
Run Code Online (Sandbox Code Playgroud)

和代码:

    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_" + …
Run Code Online (Sandbox Code Playgroud)

go

84
推荐指数
4
解决办法
12万
查看次数

标签 统计

go ×1