golang json 序列化、反序列化 字符串反序列化成 map[string]interface{}

时间:2024-10-01 16:00:36
  • // ToString 强转interface类型到string类型
  • func ToString(i interface{}) string {
  • v, _ := ToStringE(i)
  • return v
  • }
  • // ToStringE 强转interface类型到string, 支持错误返回值
  • func ToStringE(i interface{}) (string, error) {
  • i = indirectToStringerOrError(i)
  • switch s := i.(type) {
  • case string:
  • return s, nil
  • case bool:
  • return (s), nil
  • case float64:
  • return (s, 'f', -1, 64), nil
  • case float32:
  • return (float64(s), 'f', -1, 32), nil
  • case int:
  • return (s), nil
  • case int64:
  • return (s, 10), nil
  • case int32:
  • return (int(s)), nil
  • case int16:
  • return (int64(s), 10), nil
  • case int8:
  • return (int64(s), 10), nil
  • case uint:
  • return (int64(s), 10), nil
  • case uint64:
  • return (int64(s), 10), nil
  • case uint32:
  • return (int64(s), 10), nil
  • case uint16:
  • return (int64(s), 10), nil
  • case uint8:
  • return (int64(s), 10), nil
  • case []byte:
  • return string(s), nil
  • case :
  • return string(s), nil
  • case :
  • return string(s), nil
  • case :
  • return string(s), nil
  • case :
  • return string(s), nil
  • case :
  • return string(s), nil
  • case nil:
  • return "", nil
  • case :
  • return (), nil
  • case error:
  • return (), nil
  • default:
  • v := (i)
  • if method, ok := (i).MethodByName("String"); ok && () == 0 &&
  • () == 1 && (0).Kind() == {
  • return ([]{v})[0].String(), nil
  • }
  • switch () {
  • case :
  • fullName := (()).Name()
  • ss := (fullName, ".")
  • if len(ss) > 0 {
  • return ss[len(ss)-1], nil
  • } else {
  • return fullName, nil
  • }
  • case , reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, :
  • return ToStringE(())
  • case , reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  • return ToStringE(())
  • case reflect.Float64, reflect.Float32:
  • return ToStringE(())
  • case :
  • return ToStringE(())
  • case :
  • return (), nil
  • }
  • return "", ("unable to cast %#v of type %T to string", i, i)
  • }
  • }