doufei2194 2019-04-16 11:51
浏览 58
已采纳

如何检查KEY在json.RawMessage中是否存在?

I have a:

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"`

}

code:

var userList []*User
json.Unmarshal(resp.Response, &userList)

server response may be:

[{"id":1,"first_name":"name","last_name":"last","sex":2,"nickname":"","screen_name":"screen","bdate":"1.1.1"}]

or

[{"id":1,"first_name":"name","sex":2,"nickname":"","screen_name":"screen"}]

my problem when calling a nonexistent KEY error runtime "userList[0].LastName":

error: index out of range

in the first case, the server returned:

"last_name":"last" and "bdate":"1.1.1"

in the second no

When there is no user, the server returns.

[{"error_code": 0, "error_msg": "Invalid user id"}]

answer:

    if len(userList) > 0 {
            c.String(http.StatusOK, "People name: %s", userList[0].FirstName)
        } else {
            c.String(http.StatusOK, "No People: %s", login)
        }

Thank Magestro

  • 写回答

1条回答 默认 最新

  • doumixiang2227 2019-04-16 12:09
    关注

    error: index out of range means that userList have no value with index [0], not about empty LastName

    In your example all works fine: https://play.golang.org/p/WHIqgB52w_I

    A u sure that server returns valid string and that this string exists in the resp.Response?

    Try print resp.Response and look for error in other place

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里