1 回答
TA贡献1951条经验 获得超3个赞
您可以解组为var response interface{}. 一旦 json 被解组,你可以在type assertion上做一个response检查它是否是[]interface{}或map[string]interface{}从那里去。
var email string
var response interface{}
if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
return err
}
// If you are sure that the structure of the content of the response,
// given its type, is always what you expect it to be, you can use a
// quick-and-dirty type switch/assertion.
switch v := response.(type) {
case []interface{}:
email = v[0].(map[string]interface{})["email"].(string)
case map[string]interface{}:
email = v["email"].(string)
}
// But! If you're not sure, if the APIs don't provide a guarantee,
// then you should guard against panics using the comma-ok idiom
// at every step.
if s, ok := response.([]interface{}); ok && len(s) > 0 {
if m, ok := s[0].(map[string]interface{}); ok && len(m) > 0 {
email, _ = m["email"].(string)
}
} else if m, ok := response.(map[string]interface{}); ok && len(m) > 0 {
email, _ = m["email"].(string)
}
您还可以根据提供者值预先分配一个指向预期类型的指针,并将请求正文解组到其中,这将减少必要的类型断言的数量,但需要指针解引用。
var email string
var response interface{}
if provider == "google" {
response = new(map[string]interface{})
} else if provider == "github" {
response = new([]map[string]interface{})
}
if err := json.NewDecoder(r.Body).Decode(response); err != nil {
return err
}
switch v := response.(type) {
case *[]map[string]interface{}:
email = (*v)[0]["email"].(string) // no need to assert the slice element's type
case *map[string]interface{}:
email = (*v)["email"].(string)
}
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报