How do you marshal a sql.NullString such that the output is flattened to give just the value in go?

后端 未结 3 2022
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 05:18

Given a go struct

type Company struct {
    ID   int             `json:\"id\"`              
    Abn  sql.NullString  `json:\"abn,string\"`
}

w

3条回答
  •  伪装坚强ぢ
    2021-02-15 05:59

    You cannot, at least not using just sql.NullString and encoding/json.

    What you can do is to declare a custom type that embeds sql.NullString and have that custom type implement the json.Marshaler interface.

    type MyNullString struct {
        sql.NullString
    }
    
    func (s MyNullString) MarshalJSON() ([]byte, error) {
        if s.Valid {
            return json.Marshal(s.String)
        }
        return []byte(`null`), nil
    }
    
    type Company struct {
        ID   int          `json:"id"`              
        Abn  MyNullString `json:"abn,string"`
    }
    

    https://play.golang.org/p/Ak_D6QgIzLb

提交回复
热议问题