dongxie9448 2017-11-16 17:23
浏览 148
已采纳

golang在嵌套结构中解码JSON请求并将其作为blob插入DB

I have a nested struct which I am using to decode JSON request.

type Service struct {
    ID       string `json:"id,omitempty" db:"id"`
    Name     string `json:"name" db:"name"`
    Contract struct {
        ServiceTime int    `json:"service_time"`
        Region      string `json:"region"`
    } `json:"contract" db:"contract"`
}

I am using blob type to store Contract in MySQL. To make it work , I would be needing to create a different struct with Contract as string to insert in DB. Can this be done in better way by using single struct only or is there any other elegant way ?

  • 写回答

1条回答 默认 最新

  • douciping4283 2017-11-16 18:25
    关注

    This depends on what you use to talk to the database, but if you're using database/sql and a driver that provides support for this you can have your Contract type implement the Valuer interface.

    type Service struct {
        ID       string    `json:"id,omitempty" db:"id"`
        Name     string    `json:"name" db:"name"`
        Contract Contract `json:"contract" db:"contract"`
    }
    
    type Contract struct {
        ServiceTime int    `json:"service_time"`
        Region      string `json:"region"`
    }
    
    func (c *Contract) Value() (driver.Value, error) {
        if c != nil {
            b, err := json.Marshal(c)
            if err != nil {
                return nil, err
            }
            return string(b), nil
        }
        return nil, nil
    }
    

    And then when you're executing the query just pass in the Service.Contract field and the driver should call the Value method.

    sql := // INSERT INTO ...
    svc := // &Service{ ...
    db.Exec(sql, svc.ID, svc.Name, svc.Contract)
    

    And to be able to retrieve the blob back from db and unmarshal it back into Contract you can have it implement the Scanner interface, again, if a type implements this the driver is expected to call it.

    func (c *Contract) Scan(src interface{}) error {
        var data []byte
        if b, ok := src.([]byte); ok {
            data = b
        } else if s, ok := src.(string); ok {
            data = []byte(s)
        }
        return json.Unmarshal(data, c)
    }
    
    // ...
    
    sql := // SELECT * FROM ...
    svc := // &Service{ ...
    db.QueryRow(sql, 123).Scan(&svc.ID, &svc.Name, &svc.Contract)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器