diff --git a/schema/serializer.go b/schema/serializer.go index fef39d9b..9a6aa4fc 100644 --- a/schema/serializer.go +++ b/schema/serializer.go @@ -101,6 +101,9 @@ func (JSONSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, func (JSONSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) { result, err := json.Marshal(fieldValue) if string(result) == "null" { + if field.TagSettings["NOT NULL"] != "" { + return "", nil + } return nil, err } return string(result), err diff --git a/tests/serializer_test.go b/tests/serializer_test.go index 17bfefe2..a040a4db 100644 --- a/tests/serializer_test.go +++ b/tests/serializer_test.go @@ -19,6 +19,7 @@ type SerializerStruct struct { Name []byte `gorm:"json"` Roles Roles `gorm:"serializer:json"` Roles2 *Roles `gorm:"serializer:json"` + Roles3 *Roles `gorm:"serializer:json;not null"` 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 @@ -109,7 +110,7 @@ func TestSerializer(t *testing.T) { } var result SerializerStruct - if err := DB.Where("roles2 IS NULL").First(&result, data.ID).Error; err != nil { + if err := DB.Where("roles2 IS NULL AND roles3 = ?", "").First(&result, data.ID).Error; err != nil { t.Fatalf("failed to query data, got error %v", err) }