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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With