package dto import "encoding/json" type NullString struct { String string IsNull bool } // Serialization func (ns NullString) MarshalJSON() ([]byte, error) { // If Valid is true, return the JSON serialization result of String. if ns.IsNull { return []byte(`"` + ns.String + `"`), nil } // If Valid is false, return the serialization result of null. return []byte("null"), nil } // Deserialization func (ns *NullString) UnmarshalJSON(data []byte) error { // If data is null, set Valid to false and String to an empty string. if string(data) == "null" { ns.String, ns.IsNull = "", false return nil } // Otherwise, deserialize data to String and set Valid to true. if err := json.Unmarshal(data, &ns.String); err != nil { return err } ns.IsNull = true return nil }