//
// It is recommended that implementations return a buffer that is safe
// for the caller to retain and potentially mutate.
+//
+// If the returned error is a [SemanticError], then unpopulated fields
+// of the error may be populated by [json] with additional context.
+// Errors of other types are wrapped within a [SemanticError].
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
//
// The implementation must write only one JSON value to the Encoder and
// must not retain the pointer to [jsontext.Encoder].
+//
+// If the returned error is a [SemanticError], then unpopulated fields
+// of the error may be populated by [json] with additional context.
+// Errors of other types are wrapped within a [SemanticError],
+// unless it is an IO error.
type MarshalerTo interface {
MarshalJSONTo(*jsontext.Encoder) error
// unmarshaling into a pre-populated value.
//
// Implementations must not retain or mutate the input []byte.
+//
+// If the returned error is a [SemanticError], then unpopulated fields
+// of the error may be populated by [json] with additional context.
+// Errors of other types are wrapped within a [SemanticError].
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
// unmarshaling into a pre-populated value.
//
// Implementations must not retain the pointer to [jsontext.Decoder].
+//
+// If the returned error is a [SemanticError], then unpopulated fields
+// of the error may be populated by [json] with additional context.
+// Errors of other types are wrapped within a [SemanticError],
+// unless it is a [jsontext.SyntacticError] or an IO error.
type UnmarshalerFrom interface {
UnmarshalJSONFrom(*jsontext.Decoder) error
// SemanticError describes an error determining the meaning
// of JSON data as Go data or vice-versa.
//
+// If a [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom] method
+// returns a SemanticError when called by the [json] package,
+// then the ByteOffset, JSONPointer, and GoType fields are automatically
+// populated by the calling context if they are the zero value.
+//
// The contents of this error as produced by this package may change over time.
type SemanticError struct {
requireKeyedLiterals
// UnmarshalJSONFrom decodes a JSON object from dec into obj.
func (obj *OrderedObject[V]) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if k := dec.PeekKind(); k != '{' {
- return fmt.Errorf("expected object start, but encountered %v", k)
+ // The [json] package automatically populates relevant fields
+ // in a [json.SemanticError] to provide additional context.
+ return &json.SemanticError{JSONKind: k}
}
if _, err := dec.ReadToken(); err != nil {
return err