如何将 []interface 转换为 []strings 或将其转换为包含 []interface 中所有元素的连接的单个字符串?下面是显示“scope”的精确值的屏幕截图,[]interface 类型的长度为 2。在下面的代码中,case 是“slice”,目前我正在使用 reflect 进行此操作,但这看起来不太好。想知道应该有一些好的方法来连接界面元素的 slice\数组。
我也试过像这样使用 json unmarshall "json.Unmarshal([]byte(jwtResp),&mymap)"但在将 jwt.MapClaims 转换为 byte[] 时遇到类型问题
parsedkey, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(key))
parsedToken, jwtErr := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
return parsedkey, nil
})
jwtValues = make(map[string]string)
// we dont know which data types we are dealing with here, so using swtich case based on value data type
jwtResp := parsedToken.Claims.(jwt.MapClaims)
for k, v := range jwtResp {
switch reflect.TypeOf(v).Kind() {
case reflect.Slice:
fmt.Println("tp is : ", reflect.TypeOf(v)) // this is []interface{}
fmt.Println("type is : ", reflect.TypeOf(v).Kind()) // this is slice
s := reflect.ValueOf(v)
for i := 0; i < s.Len(); i++ {
jwtValues[k] += s.Index(i).Interface().(string)
jwtValues[k] += "|"
}
case reflect.String:
jwtValues[k] = v.(string)
default:
fmt.Println("unknown datatype")
}
}
最佳答案
感谢您的建议。下面是我发现用“if”条件替换“switch”以及类型断言的最接近的解决方案。 “反射(reflect)”是昂贵的。使用下面的代码,我正在查找 jwtResp
的值是否是 slice 、字符串或其他内容。如果是 slice,则遍历值([] 带有字符串类型元素的接口(interface))并将它们连接为一个串联字符串。
for k, v := range jwtResp {
if s, ok := v.(string); ok {
JwtValues[k] = s
} else if s, ok := v.([]interface{}); ok {
sslice := make([]string, len(s))
for i, v := range s {
sslice[i] = v.(string)
}
JwtValues[k] = strings.Join(sslice, "|")
} else {
logger.Log(util.LogDebug, "unknown data type")
}
}
关于golang - 将 [ ] 接口(interface)转换为 [ ] 字符串或连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659928/