mirror of https://github.com/go-gorm/gorm.git
Save as NULL for nil object serialized into json
This commit is contained in:
parent
186e8a9e14
commit
ab5f80a8d8
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
)
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue