Idiomatic way to embed struct with custom MarshalJSON() method

前端 未结 5 630
星月不相逢
星月不相逢 2021-02-04 09:30

Given the following structs:

type Person {
    Name string `json:\"name\"`
}

type Employee {
    Person
    JobRole string `json:\"jobRole\"`
}
<
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 10:10

    Nearly 4 years later, I've come up with an answer that is fundamentally similar to @jcbwlkr's, but does not require the intermediate unmarshal/re-marshal step, by using a little bit of byte-slice manipulation to join two JSON segments.

    func (e *Employee) MarshalJSON() ([]byte, error) {
        pJSON, err := e.Person.MarshalJSON()
        if err != nil {
            return nil, err
        }
        eJSON, err := json.Marshal(map[string]interface{}{
            "jobRole": e.JobRole,
        })
        if err != nil {
            return nil, err
        }
        eJSON[0] = ','
        return append(pJSON[:len(pJSON)-1], eJSON...), nil
    }
    

    Additional details and discussion of this approach here.

提交回复
热议问题