给定一个结构
type Company struct { ID int `json:"id"` Abn sql.NullString `json:"abn,string"` }
当像这样编组
company := &Company{} company.ID = 68 company.Abn = "SomeABN" result, err := json.Marshal(company)
结果是
{ "id": "68", "abn": { "String": "SomeABN", "Valid": true } }
所需的结果是
{ "id": "68", "abn": "SomeABN" }
我已经尝试过明确指出Abn是一个字符串。
Abn sql.NullString `json:"abn,string"`
并没有改变结果。
如何编组sql.NullString以便将输出展平以仅给出go中的值?
编辑
在阅读了答案后,我最终得到了类似的结果
package main import ( "database/sql" "encoding/json" "reflect" //"github.com/lib/pq" ) /* https://medium.com/aubergine-solutions/how-i-handled-null-possible-values-from-database-rows-in-golang-521fb0ee267 */ type NullString sql.NullString func (x *NullString) MarshalJSON() ([]byte, error) { if !x.Valid { x.Valid = true x.String = "" //return []byte("null"), nil } return json.Marshal(x.String) } // Scan implements the Scanner interface for NullString func (ns *NullString) Scan(value interface{}) error { var s sql.NullString if err := s.Scan(value); err != nil { return err } // if nil then make Valid false if reflect.TypeOf(value) == nil { *ns = NullString{s.String, false} } else { *ns = NullString{s.String, true} } return nil } type Company struct { ID int `json:"id"` Abn NullString `json:"abn"` }
这是代码,
package main import ( "database/sql" "encoding/json" "fmt" "log" ) //Company details type Company struct { ID int `json:"id"` Abn NullString `json:"abn"` } //NullString is a wrapper around sql.NullString type NullString sql.NullString //MarshalJSON method is called by json.Marshal, //whenever it is of type NullString func (x *NullString) MarshalJSON() ([]byte, error) { if !x.Valid { return []byte("null"), nil } return json.Marshal(x.String) } func main() { company := &Company{} company.ID = 68 //create new NullString value nStr := sql.NullString{String: "hello", Valid: true} //cast it company.Abn = NullString(nStr) result, err := json.Marshal(company) if err != nil { log.Println(err) } fmt.Println(string(result)) }
这是博客文章,详细解释了它。