Save as empty string for not nullable nil field serialized into json

This commit is contained in:
Jinzhu 2022-10-18 16:25:39 +08:00
parent ab5f80a8d8
commit a0f4d3f7d2
2 changed files with 5 additions and 1 deletions

View File

@ -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

View File

@ -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)
}