From ab5f80a8d81c1955e92224b24dfc9bc8c7d387a0 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 18 Oct 2022 15:44:47 +0800 Subject: [PATCH] Save as NULL for nil object serialized into json --- schema/serializer.go | 3 +++ tests/go.mod | 4 ++-- tests/serializer_test.go | 3 ++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/schema/serializer.go b/schema/serializer.go index 00a4f85f..fef39d9b 100644 --- a/schema/serializer.go +++ b/schema/serializer.go @@ -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 } diff --git a/tests/go.mod b/tests/go.mod index 2fef9d97..9c87ca34 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -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 ) diff --git a/tests/serializer_test.go b/tests/serializer_test.go index 946536bf..17bfefe2 100644 --- a/tests/serializer_test.go +++ b/tests/serializer_test.go @@ -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) }