A common mistake is assuming json.Marshal always encodes every exported field. A type implementing json.Marshaler can replace default encoding with MarshalJSON, which returns JSON bytes and an error. section 10.3.1
Embedded time.Time overrides Event encoding
With `type Event struct { ID int; time.Time }`, the embedded time.Time methods are promoted, so Event also implements json.Marshaler. Calling `json.Marshal(event)` therefore uses time.Time's encoder and can produce only a quoted timestamp, ignoring ID. Naming the field (`Time time.Time`) restores default struct encoding. If embedding must remain, define Event.MarshalJSON and marshal an anonymous struct containing ID and Time; keep that method synchronized with the Event fields. section 10.3.1
type Event struct {
ID int
time.Time #1
}
Inspect the embedded field that causes Event to inherit time.Time's Marshaler implementation. section 10.3.1
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
Use the interface signature to recognize when a type controls its JSON representation. section 10.3.1
Choose the correction according to the intended structure:
- Name the time.Time field when ordinary object encoding is wanted. section 10.3.1
- Implement MarshalJSON when the type needs custom output or must retain embedding. section 10.3.1
