How to not marshal an empty struct into JSON with Go?

前端 未结 4 2104
一个人的身影
一个人的身影 2020-12-04 15:22

I have a struct like this:

type Result struct {
    Data       MyStruct  `json:\"data,omitempty\"`
    Status     string    `json:\"status,omitempty\"`
    R         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 15:36

    Data is an initialized struct, so it isn't considered empty because encoding/json only looks at the immediate value, not the fields inside the struct.

    Unfortunately returning nil from json.Marhsler currently doesn't work:

    func (_ MyStruct) MarshalJSON() ([]byte, error) {
        if empty {
            return nil, nil // unexpected end of JSON input
        }
        // ...
    }
    

    You could give Result a marshaler as well, but it's not worth the effort.

    The only option, as Matt suggests, is to make Data a pointer and set the value to nil.

提交回复
热议问题