3

出于某种原因mgo,即使我设置了 omitempty 选项,也会将空结构作为空值插入到数据库中。

package main

import (
    "fmt"
    "encoding/json"
)

type A struct {
    A bool
}

type B struct {
    X       int `json:"x,omitempty" bson:"x,omitempty"`
    SomeA   *A `json:"a,omitempty" bson:"a,omitempty"`
}

func main() {
    b := B{}
    b.X = 123

    if buf, err := json.MarshalIndent(&b, "", " "); err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(string(buf))
    }
}

json 编码器省略了该SomeA属性,但在数据库中它以"a" : null. 我做错了什么,或者根本不可能这样做?

4

1 回答 1

8

Yeah, so problem was having tabs between the json and bson encoder options, that's why omitempty didn't work. So this is wrong:

SomeA   *A `json:"a,omitempty"         bson:"a,omitempty"`

Instead just have a single space and it's all good:

SomeA   *A `json:"a,omitempty" bson:"a,omitempty"`
于 2014-09-19T16:06:02.653 回答