Ama*_*aur 4 reflection interface go
我正在尝试从Golang中的接口获取字段值。该接口最初是一个空接口,正在从数据库结果中获取其值。数据库查询工作正常。
我唯一需要做的就是获取接口的字段值。这是我的代码:
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
fmt.Println(s.Index(i))
}
Run Code Online (Sandbox Code Playgroud)
其中t是具有以下值的接口:
map[id:null count:1]
Run Code Online (Sandbox Code Playgroud)
我想要"count"简单的价值1。
我的问题是Index()方法正在返回紧急消息,因为它需要一个结构,而我在这里没有任何结构。那么我该怎么做才能获得接口价值?有没有解决方案可以在有或没有Golang的反射包的情况下遍历接口以获取字段值?
编辑
获取计数值后,我需要将其解析为json。
这是我的代码:
type ResponseControllerList struct{
Code int `json:"code"`
ApiStatus int `json:"api_status"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
TotalRecord interface{} `json:"total_record,omitempty"`
}
response := ResponseControllerList{}
ratingsCount := reflect.ValueOf(ratingsCountInterface).MapIndex(reflect.ValueOf("count"))
fmt.Println(ratingsCount)
response = ResponseControllerList{
200,
1,
"success",
nil,
ratingsCount,
}
GetResponseList(c, response)
func GetResponseList(c *gin.Context, response ResponseControllerList) {
c.JSON(200, gin.H{
"response": response,
})
}
Run Code Online (Sandbox Code Playgroud)
上面的代码用于获取ratingCountJSON格式,以将此响应用作API响应。在这段代码中,我正在使用GIN框架向API发出HTTP请求。
现在的问题是,当我打印变量时ratingsCount,它在终端中显示需要的计数的确切值。但是,当我将其传递给JSON时,相同的变量给了我这样的响应:
{
"response": {
"code": 200,
"api_status": 1,
"message": "Success",
"total_record": {
"flag": 148
}
}
}
Run Code Online (Sandbox Code Playgroud)
在JSON中获取计数的实际值的方法是什么?
您可以使用类型断言而不是反射。通常最好是尽可能避免反射。
m, ok := t.(map[string]interface{})
if !ok {
return fmt.Errorf("want type map[string]interface{}; got %T", t)
}
for k, v := range m {
fmt.Println(k, "=>", v)
}
Run Code Online (Sandbox Code Playgroud)
如果您确实想使用反射,则可以执行以下操作:
s := reflect.ValueOf(t)
for _, k := range s.MapKeys() {
fmt.Println(s.MapIndex(k))
}
Run Code Online (Sandbox Code Playgroud)
更新以回复您的最新更新
它不会返回您期望的值,因为它会返回reflect.Value。如果需要整数值,则必须使用ratingsCount.Int()。
但是正如我之前说的,不要使用反射。将第一个解决方案与类型声明一起使用,并仅通过即可获得计数m["count"]。
我在这里使用类型断言发布了工作示例:https : //play.golang.org/p/9gzwtJIfd7