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 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换