【问题标题】:Golang error: interface conversion: interface {} is bool/float..., not stringGolang 错误:接口转换:接口 {} 是 bool/float...,而不是字符串
【发布时间】:2018-03-05 09:09:35
【问题描述】:

我正在尝试使用 Golang 解码任意 JSON,因此我在 map[string]interface{} 中解组传入的 JSON,如下面的代码所示:

    func JsonHandler(jsonRequest []byte) {

      // Creating the maps for JSON
      var m interface{}

      // Parsing/Unmarshalling JSON encoding/json
      if err := json.Unmarshal([]byte(jsonRequest), &m); err != nil {
            panic(err)
       }

       //Creating an output file for writing
       f, err := os.OpenFile("/home/dorrahadrich/Desktop/output.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
       if err != nil {
           panic(err)
       }

       defer f.Close()

       ParseJson(m, f, err)
   }

   func ParseJson(m interface{}, f *os.File, err error) {
       switch v := m.(interface{}).(type){
          case map[string]interface{}:
               ParseMap (m.(map[string]interface{}),f,err)
               fmt.Println(v)
          case []interface{}:
               ParseArray (m.([]interface{}),f,err)
               fmt.Println(v)
          default:
     }
 }

   func ParseMap(aMap map[string]interface{}, f *os.File, err error) {
    for key, val := range aMap {
        switch val.(type) {
        case map[string]interface{}:
            if _, err = f.WriteString(key + "={\n"); err != nil {
                panic(err)
            }

            ParseMap(val.(map[string]interface{}), f, err)

            //Close brackets
            if _, err = f.WriteString("};\n"); err != nil {
                panic(err)
            }

        case []interface{}:
            //Write to file
            if _, err = f.WriteString(key + "={\n"); err != nil {
                panic(err)
            }

            ParseArray(val.([]interface{}), f, err)

            //Close brackets
            if _, err = f.WriteString("};\n"); err != nil {
                panic(err)
            }
        default:
            otherValues(key, val.(interface{}), f , err)
        }
    }
}

func ParseArray(anArray []interface{}, f *os.File, err error) {
    for _, val := range anArray {
        switch val.(type) {
        case map[string]interface{}:
            ParseMap(val.(map[string]interface{}), f, err)
        case []interface{}:
            ParseArray(val.([]interface{}), f, err)
        default:
        }
    }

}
func otherValues(key string, other interface{}, f *os.File, err error) {
     if _, err = f.WriteString(key); err != nil {
           panic(err)
        }
    if _, err = f.WriteString("="); err != nil {
        panic(err)
        }

   switch other.(interface{}).(type) {
       case string:
           if _, err = f.WriteString(other.(string)); err != nil {
               panic(err)
            }
       case float64:
           if _, err = f.WriteString(strconv.FormatFloat(other.(float64), 'f', -1, 64)); err != nil {
                panic(err)
            }
       case bool:
    if _, err = f.WriteString(strconv.FormatBool(other.(bool))); err != nil {
                panic(err)
            }
       default:
     }  
   }

问题在于,每当 JSON 包含 bool/int/float 或任何非字符串值时,程序都会恐慌,说它无法将接口转换为给定类型!请注意,JSON 是任意的,因此我对键和值一无所知,我无法解开接口或访问给出路径的值。

【问题讨论】:

  • 解组为interface{} 类型的简单值。那对你有用吗?任何有效的 JSON 都可以解组到其中。
  • 这是因为当您将 json 解组到 interface{} 时,它还可以包含 bool/float64/string。您也必须添加相同的案例
  • 我尝试切换“val”的类型并将其转换为字符串,然后再将其传递给f.WriteString函数,仍然是同样的错误!!
  • 任何失败的 json 示例都会有所帮助
  • 您没有处理字符串、浮点数和布尔值。

标签: json go


【解决方案1】:

错误说明了一切:

接口转换:interface{} 为 bool/float64

当您解组 json 时,int 和 bool 的值不是接口类型。在您的开关中也为 bool/float64/string 添加案例。由于 json 是使用 interface{} 任意解组它们。

func otherValues(other interface{}, f *os.File, err error) {
    switch bb := other.(interface{}).(type) {
    case string:
        fmt.Println("This is a string")
    case float64:
        fmt.Println("this is a float")
    case bool:
        fmt.Println("this is a boolean")
    default:
        fmt.Printf("Default value is of type %v", bb)
    }
}

使用file.Write 代替file.WriteString

func (f *File) Write(b []byte) (n int, err error)

Write 将 len(b) 个字节写入文件。它返回字节数 写和一个错误,如果有的话。当 n != 时,写入返回非零错误 len(b)。

【讨论】:

  • 我将 JSON 解组为 interface{},然后切换了 interface{} 的真实类型,并按照您所说的添加了案例,但我仍然遇到同样的错误。
  • 显示您正在解组的 json 以及您在传递数据后尝试过的代码。你得到同样的错误吗
  • 可能是您正在使用 file.WriteString 这就是可以写入字符串的原因。您可以使用 file.Write
  • 我在您的代码中发现了一个错误并对其进行了编辑。我们需要将other.(bool) 转换为other.(interface{}).(bool)
  • 但我在使用 file.WriteString 之前将值转换为字符串!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2016-02-28
  • 2022-08-18
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多