将interface {}转换为某种类型

Shu*_*ken 8 casting go

我正在开发将接收JSON的Web服务.Go转换类型太严格了.

所以,我没有下面的函数转换interface{}bool

func toBool(i1 interface{}) bool {
    if i1 == nil {
        return false
    }
    switch i2 := i1.(type) {
    default:
        return false
    case bool:
        return i2
    case string:
        return i2 == "true"
    case int:
        return i2 != 0
    case *bool:
        if i2 == nil {
            return false
        }
        return *i2
    case *string:
        if i2 == nil {
            return false
        }
        return *i2 == "true"
    case *int:
        if i2 == nil {
            return false
        }
        return *i2 != 0
    }
    return false
}
Run Code Online (Sandbox Code Playgroud)

我认为,功能还不够完善,我需要的功能转换interface{}string,int,int64,等

所以我的问题是:是否有库(函数集)Go将转换interface{}为某些类型

UPDATE

我的Web服务收到JSON.我解码它map[string]interface{}我无法控制编码它的人.

所以我收到的所有值都是,interface{}并且我需要以某种类型转换它.

因此,它可能是nil,int,float64,string,[...],{...},我想将它转换为它应该是什么.例如int,float64,string,[]string,map[string]string与所有可能的情况处理,包括nil,错误的价值观,等等

UPDATE2

我收到{"s": "wow", "x":123,"y":true},{"s": 123, "x":"123","y":"true"},{a:["a123", "a234"]},{}

var m1 map[string]interface{}
json.Unmarshal(b, &m1)
s := toString(m1["s"])
x := toInt(m1["x"])
y := toBool(m1["y"])
arr := toStringArray(m1["a"])
Run Code Online (Sandbox Code Playgroud)

mcu*_*ros 10

objx包完全符合您的要求,它可以直接使用JSON,并为您提供默认值和其他很酷的功能:

Objx提供了objx.Map类型,它map[string]interface{} 公开了一个强大的Get方法(以及其他方法),允许您轻松快速地访问地图中的数据,而不必过多担心类型断言,缺少数据,默认值等.

这是一个小例子:

o := objx.New(m1) 
s := o.Get("m1").Str() 
x := o.Get("x").Int() 
y := o.Get("y").Bool()

arr := objx.New(m1["a"])
Run Code Online (Sandbox Code Playgroud)

来自使用JSON的doc的示例:

// use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)

// get the details
name := m.Get("name").Str()
age := m.Get("age").Int()

// get their nickname (or use their name if they
// don't have one)
nickname := m.Get("nickname").Str(name)
Run Code Online (Sandbox Code Playgroud)

显然你可以在普通运行时使用这样的东西:

switch record[field].(type) {
case int:
    value = record[field].(int)
case float64:
    value = record[field].(float64)
case string:
    value = record[field].(string)
}
Run Code Online (Sandbox Code Playgroud)

但是如果你检查objx访问器,你可以看到一个类似于这个的复杂代码,但有很多用法,所以我认为最好的解决方案是使用objx库.


Dar*_*ich 7

快速/最好的方法是在执行时“强制转换”(如果您知道该对象):

例如

package main    
import "fmt"    
func main() {
    var inter (interface{})
    inter = "hello"
    var value string
    value = inter.(string)
    fmt.Println(value)
}
Run Code Online (Sandbox Code Playgroud)

在这里试试