Golang 中国
  1. 直接上代码:

     type getRemoteCardInfo struct {
          Code int
          Msg  string
          Data []*remoteCardInfo
         }
    
     type remoteCardInfo struct {
         Sn            string
         RemoteCardIp  string
         RemoteCardMac string
     }
    
     type getremoteCard struct {
          Code int
          Msg  string
          Data []*remoteCard
         }
    
     type remoteCard struct {
         Sn            string
         RemoteXXXXX  string
         RemoteYYYYY string
         RemoteZZZZZ string
     }
    
     func Get_json_data(url string) (interface{}, error) {
     client := &http.Client{}
     req, err := http.NewRequest("GET", url, nil)
     req.Header.Add("X-MYCMDB-Auth-Token", "sPf98SMBWzOZJEJB8KWltbJyKvFYPauu")
    
     if err != nil {
         return nil, err
     }
    
     resp, _ := client.Do(req)
    
     if resp.StatusCode != http.StatusOK {
     resp.Body.Close()
     return nil, fmt.Errorf("query failed: %s", resp.Status)
     }
    
     var result interface{}
    
     body, err := ioutil.ReadAll(resp.Body)
    
     if err := json.Unmarshal(body, &result); err != nil {
     log.Fatalf("JSON unmarshaling failed: %s", err)
     }
    
     resp.Body.Close()
     fmt.Println(result)
     return result, nil
     }
    
     func main() {
         jsondata, err := Get_json_data(DHCPURL)
    
         if err != nil {
         log.Fatal(err)
         }
         switch v := jsondata.(type) {
             case getRemoteCardInfo:
                 fmt.Println("aaaa")
             case getremoteCard:
                 fmt.Println("bbbbb")
             default:
                  fmt.Printf("I don't know about type %T!\n", v)
     }
    

请问 我请求到json数据后,如何将返回值断言到我们定义的struct,我想复用这个函数,上面代码执行结果一直是 I don’t know about type map[string]interface {}!


xjg 于 2017-12-07 18:49 修改
1 回复
singlethread
#1 singlethread • 2017-12-07 18:41

29行改成

var result getRemoteCardInfo
需要 登录 后方可回复, 如果你还没有账号你可以 注册 一个帐号。