Assigning null to JSON fields instead of empty strings

后端 未结 5 1904
迷失自我
迷失自我 2020-11-29 23:34

Since empty string is the zero/default value for Go string, I decided to define all such fields as interface{} instead. for example



        
5条回答
  •  误落风尘
    2020-11-30 00:08

    Another way actually is a workaround with using the MarhshalJSON and UnmarshalJSON interface method offered by the json lib of golang. The code is as below:

    type MyType string
    type MyStruct struct {
        A MyType `json:"my_type"`
    }
    
    func (c MyType) MarshalJSON() ([]byte, error) {
        var buf bytes.Buffer
        if len(string(c)) == 0 {
            buf.WriteString(`null`)
        } else {
            buf.WriteString(`"` + string(c) + `"`)   // add double quation mark as json format required
        }
        return buf.Bytes(), nil
    }
    
    func (c *MyType)UnmarshalJSON(in []byte) error {
        str := string(in)
        if str == `null` {
            *c = ""
            return nil
        }
        res := MyType(str)
        if len(res) >= 2 {
            res = res[1:len(res)-1]     // remove the wrapped qutation
        }
        *c = res
        return nil
    }
    

    then when using json.Marshal, the MyType value will be marshaled as null.

提交回复
热议问题