如何以一种好的方式使用 SQL NULL 值和 JSON? [英] How can I work with SQL NULL values and JSON in a good way?

查看:33
本文介绍了如何以一种好的方式使用 SQL NULL 值和 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Int64String 这样的 Go 类型不能存储空值,所以我发现我可以使用 sql.NullInt64sql.NullString 为此.

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 包从结构中生成 JSON,那么格式与我使用常规 Int64String 类型时的格式不同.

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.

JSON 有一个额外的级别,因为 sql.Null*** 也是一个 Struct.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆