how to read Mysql json column to an embedded struct using Gorm

huangapple go评论85阅读模式
英文:

how to read Mysql json column to an embedded struct using Gorm

问题

我正在尝试使用gorm将列读取到嵌入的结构体中,表中有一个Json列,我想将其读取为一个定义好的结构体。我该如何实现这个目标?

type Permissions struct {
   // 所有其他列
   Rules []Rule // 这个在数据库中保存为一个json列
}

type Rule struct {
  // 这里也可以嵌入其他列
}
英文:

I am trying to read columns to an embedded struct usng gorm, the table has a Json column and I would like to read it a defined struct. How can I achieve this one ??

type Permissions struct {
   // all other columns 
   Rules []Rule // this is saved as a json column in db  
}

type Rule struct {
  // embedded columns here too 
}

答案1

得分: 2

自定义数据类型是被支持的,你只需要为你的自定义类型实现ScannerValuer接口。代码可能如下所示:

func (r *Rule) Scan(value interface{}) error {
  val, ok := value.([]byte)
  if !ok {
    return errors.New(fmt.Sprint("无法解组字符串值:", value))
  }

  return json.Unmarshal([]byte(val), r)
}

func (r Rule) Value() (driver.Value, error) {
  val, err := json.Marshal(&r)
  if err != nil {
    return nil, err
  }

  return val, nil
}
英文:

Custom data types are supported, you would just need to implement the Scanner and Valuer interfaces for your custom type. It could look something like this:

func (r *Rule) Scan(value interface{}) error {
  val, ok := value.([]byte)
  if !ok {
    return errors.New(fmt.Sprint("Failed to unmarshal string value:", value))
  }

  return json.Unmarshal([]byte(val), r)
}

func (r Rule) Value() (driver.Value, error) {
  val, err := json.Marshal(&r)
  if err != nil {
    return nil, err
  }
  
  return val, nil
}

huangapple
  • 本文由 发表于 2021年8月25日 13:04:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/68917049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定