我有一个:
type User struct {
UID int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Sex int `json:"sex"`
Nickname string `json:"nickname"`
ScreenName string `json:"screen_name"`
BDate string `json:"bdate"`
}
法典:
var userList []*User
json.Unmarshal(resp.Response, &userList)
服务器响应可能是:
[{"id":1,"first_name":"name","last_name":"last","sex":2,"nickname":"","screen_name":"screen","bdate":"1.1.1"}]
或
[{"id":1,"first_name":"name","sex":2,"nickname":"","screen_name":"screen"}]
调用不存在的 KEY 错误运行时"userList[0].LastName
"时我的问题:
error: index out of range
在第一种情况下,服务器返回:
"last_name":"last" and "bdate":"1.1.1"
在第二个没有
当没有用户时,服务器将返回。
[{"error_code": 0, "error_msg": "Invalid user id"}]
答:
if len(userList) > 0 {
c.String(http.StatusOK, "People name: %s", userList[0].FirstName)
} else {
c.String(http.StatusOK, "No People: %s", login)
}
谢谢马格斯特罗
error: index out of range
表示userList
与索引[0]
没有值,而不是空LastName
在您的示例中,一切正常:https://play.golang.org/p/WHIqgB52w_I
确定服务器返回有效的字符串并且此字符串存在于resp.Response
中?
尝试打印resp.Response
并在其他地方查找错误