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

前端 未结 4 2116
一个人的身影
一个人的身影 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

    As the docs say, "any nil pointer." -- make the struct a pointer. Pointers have obvious "empty" values: nil.

    Fix - define the type with a struct pointer field:

    type Result struct {
        Data       *MyStruct `json:"data,omitempty"`
        Status     string    `json:"status,omitempty"`
        Reason     string    `json:"reason,omitempty"`
    }
    

    Then a value like this:

    result := Result{}
    

    Will marshal as:

    {}
    

    Explanation: Notice the *MyStruct in our type definition. JSON serialization doesn't care whether it is a pointer or not -- that's a runtime detail. So making struct fields into pointers only has implications for compiling and runtime).

    Just note that if you do change the field type from MyStruct to *MyStruct, you will need pointers to struct values to populate it, like so:

    Data: &MyStruct{ /* values */ }
    

提交回复
热议问题