liveBook · Manning

Marshaler interface

As explained in 100 Go Mistakes and How to Avoid Them

json.Marshaler is a Go interface for types that provide custom JSON encoding through a MarshalJSON method.

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

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the interface signature, method promotion, observable output, and two fixes, while deferring broader encoding internals.
Examples
Uses foo custom encoding and Event with embedded or named time.Time to contrast replacement and default JSON output.
What it assumes
Assumes familiarity with Go structs, interfaces, embedded fields, and method promotion.
What you can do after
Diagnose overridden JSON output and choose field naming or a custom MarshalJSON implementation.
How it connects
Connects custom JSON encoding with Go interfaces, embedded fields, method promotion, time.Time, json.Marshal, and json.Unmarshal.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.