如何以一种好的方式使用SQL NULL值和JSON? [英] How can I work with SQL NULL values and JSON in a good way?
问题描述
像Int64
和String
这样的Go类型不能存储空值,
因此我发现可以使用 sql.NullInt64 和
Go types like Int64
and String
cannot store null values,
so I found I could use sql.NullInt64 and sql.NullString for this.
但是当我在Struct中使用它们时,
并使用 json 包从Struct生成JSON,
那么格式与我使用常规Int64
和String
类型的格式不同.
But when I use these in a Struct,
and generate JSON from the Struct with the json package,
then the format is different to when I use regular Int64
and String
types.
由于sql.Null ***也是结构,因此JSON具有附加级别.
The JSON has an additional level because the sql.Null*** is also a Struct.
是否有一个很好的解决方法, 还是不应该在我的SQL数据库中使用NULL?
Is there a good workaround for this, or should I not use NULLs in my SQL database?
推荐答案
类似sql.NullInt64
的类型对JSON封送或拆组不执行任何特殊处理,因此适用默认规则.由于类型是结构,因此将其编组为对象,并将其字段作为属性.
Types like sql.NullInt64
do not implement any special handling for JSON marshaling or unmarshaling, so the default rules apply. Since the type is a struct, it gets marshalled as an object with its fields as attributes.
解决此问题的一种方法是创建自己的类型,以实现json.Marshaller
/json.Unmarshaler
接口.通过嵌入sql.NullInt64
类型,我们可以免费获得SQL方法.像这样:
One way to work around this is to create your own type that implements the json.Marshaller
/ json.Unmarshaler
interfaces. By embedding the sql.NullInt64
type, we get the SQL methods for free. Something like this:
type JsonNullInt64 struct {
sql.NullInt64
}
func (v JsonNullInt64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Int64)
} else {
return json.Marshal(nil)
}
}
func (v *JsonNullInt64) UnmarshalJSON(data []byte) error {
// Unmarshalling into a pointer will let us detect null
var x *int64
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.Int64 = *x
} else {
v.Valid = false
}
return nil
}
如果使用此类型代替sql.NullInt64
,则应按预期进行编码.
If you use this type in place of sql.NullInt64
, it should be encoded as you expect.
您可以在此处测试此示例: http://play.golang.org/p/zFESxLcd-c
You can test this example here: http://play.golang.org/p/zFESxLcd-c
这篇关于如何以一种好的方式使用SQL NULL值和JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!