Int64String这样的围棋类型不能存储空值, 所以我发现我可以用sql.NullInt64sql.NullString来做这个.

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.

Is there a good workaround for this, or should I not use NULLs in my SQL 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.

你可以在这里测试这个例子:http://play.golang.org/p/zFESxLcd-c

Json相关问答推荐

如何使用表键名称GROUP_BY

Jolt将键和值转换为单独的数组集

如何在PowerShell中访问嵌套的JSON字段

使用PowerShell解析文件并获取特定行的值

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

在深度嵌套数组中使用布尔属性的jq-select

规范化JSON数据

如何避免解析 ISuperObject 类型字段中的 json 对象

Golang jsonrpc2 服务器在哪里监听?

JOLT转换并向输出添加新数组

小写嵌套特定键的震动转换

从 PySpark 中的复杂 JSON 文件中高效清除 HTML 实体

如何使用 jq 返回此 JSON 文件的文本字段?

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

如何在 Go 中生成带有排序键的 JSON?

单元测试球衣 Restful Services

未捕获的类型错误:无法读取 null 的属性props

Qt使用QJsonDocument、QJsonObject、QJsonArray解析JSON

Peewee 模型转 JSON

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性