Idiomatic way to embed struct with custom MarshalJSON() method

前端 未结 5 569
星月不相逢
星月不相逢 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:11

    Don't put MarshalJSON on Person since that's being promoted to the outer type. Instead make a type Name string and have Name implement MarshalJSON. Then change Person to

    type Person struct {
        Name Name `json:"name"`
    }
    

    Example: https://play.golang.org/p/u96T4C6PaY


    Update

    To solve this more generically you're going to have to implement MarshalJSON on the outer type. Methods on the inner type are promoted to the outer type so you're not going to get around that. You could have the outer type call the inner type's MarshalJSON then unmarshal that into a generic structure like map[string]interface{} and add your own fields. This example does that but it has a side effect of changing the order of the final output fields

    https://play.golang.org/p/ut3e21oRdj

提交回复
热议问题