在编组下面的Foo实例时,如何在实现json marshaler接口时获取标记信息?请注意,我们也可以使用Bar结构,它也使用MyNullString . 所以我们不能假设MyNullString只被Foo结构使用 .
包主
import (
"fmt"
"database/sql"
"encoding/json"
)
type MyNullString struct {
sql.NullString
}
type Foo struct {
MyInt int64
MyString MyNullString `json:"my_string,omitempty"`
}
func (s *MyNullString) MarshalJSON() ([]byte, error){
//Inspect tag of struct instance and see if this field has to be omitted when empty
//HOW?????
//Note: We can use MyNullString in other structs as well.
}
func main(){
foo := Foo{MyInt: 1}
data, _ := json.Marshal(&foo)
fmt.Println(string(data))
}
1 回答
它's not possible for a type to inspect other types/values that contain it (you can' t看到're in, but you can see the boxes in you). There is an open feature request for custom omitempty support, such that a type can inform the encoder that it'的"empty"值框,但此时没有任何可用的东西 . 见http://golang.org/issue/4357