Skip to content

encoding/json: Marshaler/Unmarshaler not stream friendly #12001

Closed
@lukescott

Description

@lukescott

The Marshaler/Unmarshaler interface deals with whole []byte slices:

type Marshaler interface {
        MarshalJSON() ([]byte, error)
}
type Unmarshaler interface {
        UnmarshalJSON([]byte) error
}

If you're dealing with a type that encodes to an array that has a large number of objects inside you have to encode all of into a single []byte.

The encoding/xml package is, unlike encoding/json, stream friendly:

type Marshaler interface {
        MarshalXML(e *Encoder, start StartElement) error
}
type Unmarshaler interface {
        UnmarshalXML(d *Decoder, start StartElement) error
}

With MarshalXML you can call e.Encode/e.EncodeElement/e.EncodeToken.

Since encoding/json is gaining Token()/EncodeToken() methods it would be really helpful to have a Marshaler/Unmarshaler interface that can take advantage of that. Perhaps something along the lines of:

type Encoder interface {
        EncodeJSON(e *Encoder) error
}
type Decoder interface {
        DecodeJSON(d *Decoder) error
}

Since Marshaler/Unmarshaler can't be changed. Or something like:

type Marshaler2 interface {
        MarshalJSON(e *Encoder) error
}
type Unmarshaler2 interface {
        UnmarshalJSON(d *Decoder) error
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions