如何以良好的方式在Golang中使用sql NULL值和JSON? [英] How can I work with sql NULL values and JSON in Golang in a good way?
问题描述
可以使用sql.NullInt64和sql.NullString。
但是当我在结构中使用这些并从结构中生成JSON时JSON包,那么格式不是当我使用常规的int64和字符串时它曾经是如何。我的意思是它有一个额外的级别,因为sql.null ***也是一个结构。
有没有很好的解决方法,或者我不应该在我的MySQL数据库中使用NULL?
类型像 sql.NullInt64
请勿对JSON封送处理或解组处理实施任何特殊处理,因此应用默认规则。由于该类型是一个结构体,因此它被作为一个对象与其字段作为属性进行编组。
解决此问题的一种方法是创建您自己的类型, code> json.Marshaller / json.Unmarshaler
接口。通过嵌入 sql.NullInt64
类型,我们可以免费获得SQL方法。像这样:
type JsonNullInt64 struct {
sql.NullInt64
}
func(v JsonNullInt64)MarshalJSON()([] byte,error){
if v.Valid {
return json.Marshal(v.Int64)
} else {
返回json.Marshal(nil)
}
}
func(v * JsonNullInt64)UnmarshalJSON(data [] byte)error {
// Unmarshalling into a指针会让我们检测出null
var x * int64
if err:= json.Unmarshal(data,& x); err!= nil {
return err
}
if x!= nil {
v.Valid = true
v.Int64 = * x
}其他{
v.Valid = false
}
返回零
}
如果您使用此类型代替 sql.NullInt64
,它应该按照您的预期编码。
你可以在这里测试这个例子: http://play.golang.org/p/zFESxLcd-c
Go values like int64, string can not store null values. So I found out that we could use sql.NullInt64 and sql.NullString.
But when I use these in a struct and generate JSON from the struct with the JSON package then the format is not how it used to be when I used regular int64 and string. What I mean is that it has an additional level because the sql.Null*** is also a struct.
Is there a good workaround for this, or should I not use NULLs in my MySQL database?
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.
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
}
If you use this type in place of sql.NullInt64
, it should be encoded as you expect.
You can test this example here: http://play.golang.org/p/zFESxLcd-c
这篇关于如何以良好的方式在Golang中使用sql NULL值和JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!