duanguoping2016 2017-12-07 10:44
浏览 174

如何判断golang的解组json接口{}类型?

I want to judge json type,but it always return "I don't know about type map[string]interface {}!",How to resolve it.

=========================================================================

type getRemoteCardInfo struct {
  Code int
  Msg  string
  Data []*remoteCardInfo
 }
type remoteCardInfo struct {
 Sn            string
 RemoteCardIp  string
 RemoteCardMac 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")
       default:
          fmt.Printf("I don't know about type %T!
", v)
       }
  • 写回答

1条回答 默认 最新

  • douqiang5933 2017-12-07 20:41
    关注

    The go JSON unmarshaler doesn't know about types, as you can tell by the fact that it stores the result into an interface{} value:

    func Unmarshal(data []byte, v interface{}) error
    // "v" can be any type -------^
    

    So it's up to you to use the unmarshaler to populate your structure and determine if the result is valid or not.

    In your example it looks like you're trying to unmarshal a remoteCardInfo from an HTTP response. To do this you should unmarshal into an empty remoteCardInfo struct and determine if the required fields were populated.

    For example, suppose you expect a JSON document like so:

    {
      "sn": "123",
      "ip": "0.0.0.0",
      "mac": "ff:ff:ff:ff:ff:ff"
    }
    

    Then you should define your "remoteCardInfo" struct as below:

    type remoteCardInfo struct {
      Sn            string `json:"sn"`
      RemoteCardIp  string `json:"ip"`
      RemoteCardMac string `json:"mac"`
    }
    

    And then unmarshal and validate it like so:

    func getRemoteCardInfo(bs []byte) (*remoteCardInfo, error) {
      rci := remoteCardInfo{}
      err := json.Unmarshal(bs, &rci)
      if err != nil {
        return nil, err
      }
      // Validate the expected fields
      if rci.Sn == "" {
        return nil, fmt.Errorf(`missing "sn"`)
      }
      if rci.RemoteCardIp == "" {
        return nil, fmt.Errorf(`missing "ip"`)
      }
      if rci.RemoteCardMac == "" {
        return nil, fmt.Errorf(`missing "mac"`)
      }
      return &rci, nil
    }
    

    Of course, you can validate the fields any way you like but the main thing to remember is that the unmarshaler only does the job of ensuring that the input byte array is a valid JSON document and populates the fields from the document into the fields defined by the value.

    It cannot tell you what "type" of object the JSON document represents.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。