I have a struct Base
:
type Base struct {
Name string `json:"name,omitempty"`
// ... other fields
}
And two more structs that embed Base
:
type First struct {
Base
// ... other fields
}
type Second struct {
Base
// ... other fields
}
Now I want to Marshal the structs First
and Second
but with a little difference. I want to include the Name
field in First
but I don't want to include it in Second
.
Or to simplify the question I want to opt in and out a struct's field in its JSON dynamically.
Note: The Name
value always has value and I don't want to change it.
Try something like this:
type Base struct {
Name string `json: "name,omitempty"`
// ... other fields
}
type First struct {
Base
// ... other fields
}
type Second struct {
Base
Name string `json: "-"`
// ... other fields
}
This means you must not call Second.Base.Name anymore in the code but just Second.Name.
You can implement the Marshaler
interface for type Second
and create a dummy type SecondClone
.
type SecondClone Second
func (str Second) MarshalJSON() (byt []byte, err error) {
var temp SecondClone
temp = SecondClone(str)
temp.Base.Name = ""
return json.Marshal(temp)
}
This will work with no other changes to your code.
And it won't modify the value in Name
as it works on a different type / copy.