drfqfuhej48511519 2017-10-16 19:23
浏览 29
已采纳

解码二级响应主体以构造

I have 2 structs:

type List struct {
    ListID string `json:"listid"`
    Name string `json:"name"`
    Users []User `json:"users"`
}

type User struct {
    Email string `json:"email"`
    Name string `json:"name"`
}

I am calling an endpoint and successfully getting a response which has the structure below:

{
 "Results":[
  {"Email": "user1@domain.com", "Name": "test1" "State": "Active",…},
  {"Email": "user2@domain.com", "Name": "test2" "State": "Active",…},
  {"Email": "user3@domain.com", "Name": "test3", "State": "Active",…}
 ],
 "SomeOtherStuff": "email"
}

I am trying to decode the JSON response to my struct like this:

err = json.NewDecoder(response.Body).Decode(&list.Users)

But there is no "Results" attribute in my struct to map to. How can I map only the Results key of the response to my array of User structs ?

  • 写回答

1条回答 默认 最新

  • douhan5853 2017-10-16 19:42
    关注

    To get your data there are at least two options:

    Decode into map[string]interface{}

    m := create(map[string]interface{})
    err = json.NewDecoder(response.Body).Decode(&m)
    

    Then use the m["results"] key to get at your users.

    Or you could Decode into a container struct then assign list.Users = container.Results.

    type Container struct {
        Results []User `json:"Results"`
        SomeOtherStuff string `json:"SomeOtherStuff"`
    }
    

    To get an idea of structs for arbitrary json look at json2go.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分