package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Dome struct {
gorm.Model
Location Location `json:"location" gorm:"serializer:json"`
Title string `json:"title" gorm:"type:varchar(100)"`
}
type Location struct {
X1 int
Y1 int
X2 int
Y2 int
}
func main() {
db, _ := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
/*err := db.AutoMigrate(&Dome{})
if err != nil {
return
}*/
l := Location{}
l.Y1 = 1
l.X1 = 2
l.X2 = 3
l.Y2 = 4
d := Dome{}
d.Title = "test"
d.Location = l
db.Create(&d)
d.Location.Y2 = 6
db.Save(&d)
d.Location.X2 = 4
db.Updates(&d)
_target := []*Dome{}
db.Find(&_target)
for _, t := range _target {
fmt.Printf("%+v \n", t)
}
}
我try 了这种方式和序列化程序:JSON工作起来没有任何问题.
输出:
&{Model:{ID:1 CreatedAt:2022-08-06 14:39:59.184012808 +0530 +0530 UpdatedAt:2022-08-06 14:39:59.184012808 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:3 Y2:4} Title:test}
&{Model:{ID:2 CreatedAt:2022-08-06 14:40:55.666162544 +0530 +0530 UpdatedAt:2022-08-06 14:40:55.677998201 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:3 Y2:6} Title:test}
&{Model:{ID:3 CreatedAt:2022-08-06 14:41:29.361814733 +0530 +0530 UpdatedAt:2022-08-06 14:41:29.367237119 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:4 Y2:6} Title:test}
根据文档,您可以注册序列化程序并实现如何序列化和反序列化数据.
https://gorm.io/docs/serializer.html#Register-Serializer个