Skip to content

Commit

Permalink
Save as empty string for not nullable nil field serialized into json
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Oct 18, 2022
1 parent ab5f80a commit a0f4d3f
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 3 additions & 0 deletions schema/serializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion tests/serializer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down

0 comments on commit a0f4d3f

Please sign in to comment.