简体   繁体   English

Golang 错误:接口转换:接口 {} 是 bool/float...,而不是字符串

[英]Golang error: interface conversion: interface {} is bool/float..., not string

I am trying to decode an arbitrary JSON using Golang, so I unmarshal the incoming JSON in a map[string]interface{} as shown in the code below:我正在尝试使用 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:
     }  
   }

The problem is that whenever a JSON contains a bool/int/float or any not string value the program panics saying that it fails converting an interface to the given type!问题是,只要 JSON 包含 bool/int/float 或任何非字符串值,程序就会恐慌,说它无法将接口转换为给定类型! Please note that the JSON is arbitrary so I don't have any idea about the keys nor the values, I can't unmrashal into an interface nor access the values giving a path.请注意,JSON 是任意的,所以我对键和值一无所知,我无法解组到接口中,也无法访问给出路径的值。

The error says it all:错误说明了一切:

interface conversion: interface{} is bool/float64接口转换:interface{} 是 bool/float64

when you are unmarshalling json the values for int and bool which are not of interface type.当您解组 json 时,不是接口类型的 int 和 bool 值。 In your switch add case for bool/float64/string too.在您的开关中也为 bool/float64/string 添加 case。 Since json is arbitrary unmarshal them using interface{}.由于 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)
    }
}

Use file.Write in place of file.WriteString使用file.Write代替 file.WriteString

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

Write writes len(b) bytes to the File. Write 将 len(b) 个字节写入文件。 It returns the number of bytes written and an error, if any.它返回写入的字节数和错误(如果有)。 Write returns a non-nil error when n != len(b).当 n != len(b) 时,Write 返回一个非零错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM