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

后端 未结 2 2154
离开以前
离开以前 2021-02-15 05:37

Given a go struct

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

w

2条回答
  •  终归单人心
    2021-02-15 05:55

    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

提交回复
热议问题