Save as NULL for nil object serialized into json

This commit is contained in:
Jinzhu 2022-10-18 15:44:47 +08:00
parent 186e8a9e14
commit ab5f80a8d8
3 changed files with 7 additions and 3 deletions

View File

@ -100,6 +100,9 @@ func (JSONSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value,
// Value implements serializer interface
func (JSONSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) {
result, err := json.Marshal(fieldValue)
if string(result) == "null" {
return nil, err
}
return string(result), err
}

View File

@ -7,10 +7,10 @@ require (
github.com/jinzhu/now v1.1.5
github.com/lib/pq v1.10.7
golang.org/x/crypto v0.0.0-20221012134737-56aed061732a // indirect
golang.org/x/text v0.3.8 // indirect
golang.org/x/text v0.4.0 // indirect
gorm.io/driver/mysql v1.4.3
gorm.io/driver/postgres v1.4.4
gorm.io/driver/sqlite v1.4.2
gorm.io/driver/sqlite v1.4.3
gorm.io/driver/sqlserver v1.4.1
gorm.io/gorm v1.24.0
)

View File

@ -18,6 +18,7 @@ type SerializerStruct struct {
gorm.Model
Name []byte `gorm:"json"`
Roles Roles `gorm:"serializer:json"`
Roles2 *Roles `gorm:"serializer:json"`
Contracts map[string]interface{} `gorm:"serializer:json"`
JobInfo Job `gorm:"type:bytes;serializer:gob"`
CreatedTime int64 `gorm:"serializer:unixtime;type:time"` // store time in db, use int as field type
@ -108,7 +109,7 @@ func TestSerializer(t *testing.T) {
}
var result SerializerStruct
if err := DB.First(&result, data.ID).Error; err != nil {
if err := DB.Where("roles2 IS NULL").First(&result, data.ID).Error; err != nil {
t.Fatalf("failed to query data, got error %v", err)
}