普通网友 2019-07-19 09:08
浏览 19

具有嵌套有效负载的JSON绑定

I'm using Go and Buffalo to develop an API. When receiving a request, it is possible to automatically map the JSON payload to a struct:

func MyAction(c buffalo.Context) error {
  u := &User{}
  if err := c.Bind(u); err != nil {
    return err
  }
  u.Name // "Ringo"
  u.Email // "ringo@beatles.com"
} 

However, it supposes that the payload is of this shape:

{
  "name": "Ringo",
  "email": "ringo@beatles.com"
}

If for some reason, the incoming payload has a key:

{
 "user": {
    "name": "Ringo",
    "email": "ringo@beatles.com"
  } 
}

The binding won't work. I couldn't find how to handle this case. How should I approach this ?

  • 写回答

1条回答 默认 最新

  • dongxia9620 2019-07-19 09:16
    关注

    Perhaps you can wrap your struct with map[string]User{}, here is an example:

    func MyAction(c buffalo.Context) error {
      u := map[string]User{
        "user": User{},
      }
      if err := c.Bind(&u); err != nil {
        return err
      }
      user := u["user"]
      user.Name // "Ringo"
      user.Email // "ringo@beatles.com"
    } 
    

    In my opinion define a struct would be cleaner solution:

    type UserObject struct {
        User struct {
            Email string
            Name  string
        }
    }
    
    func MyAction(c buffalo.Context) error {
       u := UserObject{}
       if err := c.Bind(&u); err != nil {
          return err
       }
       user := u.User
       user.Name // "Ringo"
       user.Email // "ringo@beatles.com"
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM