How to Use the encoding.TextMarshaler and encoding.TextUnmarshaler Interfaces

Implement MarshalText and UnmarshalText methods on your type to control how it converts to and from text for JSON and other encoders.

Implement MarshalText() to convert your type to a byte slice and UnmarshalText() to parse a byte slice back into your type. The encoding/json package automatically uses these methods when marshaling or unmarshaling your type.

type MyType struct {
    Value int
}

func (m MyType) MarshalText() ([]byte, error) {
    return []byte(fmt.Sprintf("%d", m.Value)), nil
}

func (m *MyType) UnmarshalText(text []byte) error {
    n, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    m.Value = n
    return nil
}