问题描述

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

I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I don't know how to do it properly.

这是错误消息:

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

推荐答案

代替

iAreaId := int(val)
iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version 

您不能转换接口类型的值的原因是参考规范部分中的以下规则:

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

T(x)Tx
T(x)Tx

...

在以下任何一种情况下,非恒定值x都可以转换为T型:

A non-constant value x can be converted to type T in any of these cases:

  1. x可分配给T.
  2. x的类型和T具有相同的基础类型.
  3. x的类型和T是未命名的指针类型,并且它们的指针基类型具有相同的基础类型.
  4. x的类型和T都是整数或浮点类型.
  5. x的类型和T都是复数类型.
  6. x是整数或字节或runes的切片,T是字符串类型.
  7. x是一个字符串,T是一个字节或符文切片.

但是

iAreaId := int(val)

不是 情况1.-7中的任何一种.

is not any of the cases 1.-7.

这篇关于将interface {}转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!