Flattening sql.NullString Output During JSON Marshaling
When marshaling a Go struct containing an sql.NullString field, the default output includes the field's Valid and String properties. To achieve a flattened output that only includes the value, you must take additional steps.
Consider the following struct:
type Company struct { ID int `json:"id"` Abn sql.NullString `json:"abn,string"` }
Marshalling this struct with json.Marshal produces an output that looks like:
{ "id": "68", "abn": { "String": "SomeABN", "Valid": true } }
Extend sql.NullString for Custom JSON Marshaling
To flatten this output, you must extend sql.NullString and implement json.Marshaler.
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) }
Define a Custom Type for Flattened Output
Next, define a custom type that embeds the extended NullString and implements json.Marshaler.
type MyNullString struct { 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"` }
By using this custom type, the marshaled output becomes:
{ "id": "68", "abn": "SomeABN" }
The above is the detailed content of How to Flatten sql.NullString Output When Marshaling JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!