duanlu9970 2017-09-27 11:11
浏览 69
已采纳

从接口获取接口字段值,而无需在Golang中声明结构

I am trying to get field values from an interface in Golang. The interface is initially an empty interface which is getting its values from a database result. The DB query is working fine.

The only thing I need is that I need to get the field value of the interface. Here is my code:

s := reflect.ValueOf(t)
    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
    }

where t is an interface having following values:

map[id:null count:1]

I want value of "count" like simply 1.

My problem is that the Index() method is returning a panic because it needs a struct and I dont have any struct here. So what should I do to get interface value? Is there any solution to iterate over an interface to get field values with or without Golang's reflection package?

Edit

After getting the value for count I need to parse it to json.

Here is my code:

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,
    })
}

The above code is being used to get the ratingCount in JSON format to use this response as API response. In this code, I am using the GIN framework to make HTTP request to API.

Now the problem is that when I am printing the variable ratingsCount, its displaying the exact value of count in terminal what I need. But when I am passing it to JSON, the same variable gives me the response like:

{
    "response": {
        "code": 200,
        "api_status": 1,
        "message": "Success",
        "total_record": {
            "flag": 148
        }
    }
}

What is the way to get the count's actual value in JSON ?

  • 写回答

1条回答 默认 最新

  • duanbiaoshu2021 2017-09-27 12:02
    关注

    You can use type assertion instead of reflection. It is generally better to avoid reflection whenever you can.

    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)
    }
    

    If you really want to use reflection, you can do something like this:

    s := reflect.ValueOf(t)
    for _, k := range s.MapKeys() {
        fmt.Println(s.MapIndex(k))
    }
    

    Update to reply to your latest update

    It does not return what you expect because it returns a reflect.Value. If you want an integer value, you have to use ratingsCount.Int().

    But as I said before, don't use reflection. Use the first solution with type assertion and just get the count with m["count"].

    I posted working example there using type assertion: https://play.golang.org/p/9gzwtJIfd7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。