jsoncodec

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package jsoncodec implements JSON marshaling and unmarshaling for protobuf messages. It follows the canonical protobuf JSON mapping specification, operating through the protoreflect.Message reflection API so that both generated types and dynamic messages are supported uniformly.

The top-level Marshal and Unmarshal functions use default options. For customization, use MarshalOptions and UnmarshalOptions directly.

Index

Constants

This section is empty.

Variables

View Source
var ErrMaxDepthExceeded = errors.New("jsoncodec: maximum recursion depth exceeded")

ErrMaxDepthExceeded is returned when the JSON input exceeds the configured recursion depth limit during unmarshaling.

View Source
var ErrMaxTokenCountExceeded = errors.New("jsoncodec: maximum token count exceeded")

ErrMaxTokenCountExceeded is returned when the JSON input contains more tokens than the configured maximum, aborting runaway unmarshal operations.

Functions

func Marshal

func Marshal(msg proto.Message) ([]byte, error)

Marshal serializes a protobuf message to canonical JSON using default options. It panics if msg is nil.

func Unmarshal

func Unmarshal(data []byte, msg proto.Message) error

Unmarshal deserializes JSON data into a protobuf message using default options. It panics if msg is nil.

Types

type MarshalError

type MarshalError struct {
	// Field is the full name of the field being marshaled, if known.
	Field string
	// Detail is a human-readable description of the failure.
	Detail string
	// Cause is the underlying error, if any.
	Cause error
}

MarshalError is a typed error returned when JSON marshaling fails. It includes the field context where available and wraps an optional cause.

func (*MarshalError) Error

func (e *MarshalError) Error() string

Error returns a human-readable message describing the marshal failure.

func (*MarshalError) Unwrap

func (e *MarshalError) Unwrap() error

Unwrap returns the underlying cause so that errors.Is and errors.As work.

type MarshalOptions

type MarshalOptions struct {
	// EmitDefaultValues emits fields with zero values instead of omitting them.
	// When false (the default), fields holding the zero value for their type
	// are omitted from the JSON output.
	EmitDefaultValues bool

	// UseProtoNames uses proto field names as JSON keys instead of camelCase.
	// When false (the default), field names are converted to lowerCamelCase
	// per the protobuf JSON mapping specification.
	UseProtoNames bool

	// UseEnumNumbers emits enum fields as numeric values instead of string names.
	// When false (the default), enum values are represented by their name strings.
	UseEnumNumbers bool

	// Deterministic causes map fields to be serialized with keys in sorted
	// order: bool false before true, integers numerically, strings
	// lexicographically. When false (the default), map iteration order is
	// undefined.
	Deterministic bool

	// Canonical enables fully deterministic JSON output suitable for
	// content-addressable hashing. When true, forces Deterministic,
	// UseProtoNames, and empty Indent.
	Canonical bool

	// AllowPartial allows marshaling a message that has missing required fields.
	// When false (the default), Marshal returns ErrRequiredNotSet if any proto2
	// required field is not set. When true, required field validation is skipped.
	AllowPartial bool

	// Multiline is a convenience flag that enables multiline indented output.
	// When true and Indent is empty, Indent defaults to two spaces ("  ").
	// When Indent is already set, Multiline has no additional effect.
	Multiline bool

	// Indent specifies the indentation string for pretty-printed output.
	// An empty string produces compact single-line JSON.
	Indent string

	// Resolver is an optional resolver used for resolving Any type URLs
	// during marshaling. Any implementation of registry.MessageResolver is
	// accepted, enabling dependency inversion: callers can supply a
	// *registry.TypeRegistry or any custom resolver. When nil,
	// registry.GlobalTypes is used.
	Resolver registry.MessageResolver
}

MarshalOptions configures JSON marshaling behavior.

fieldalignment: fields ordered for semantic clarity, not padding

func (MarshalOptions) Marshal

func (o MarshalOptions) Marshal(msg proto.Message) ([]byte, error)

Marshal serializes a protobuf message to JSON using the configured options. When Canonical is true, Deterministic, UseProtoNames, and empty Indent are forced internally without mutating the caller's options. When Multiline is true and Indent is empty, Indent defaults to two spaces. When AllowPartial is false, required fields are validated before encoding. It panics if msg is nil.

type UnmarshalError

type UnmarshalError struct {
	// Field is the full name of the field being unmarshaled, if known.
	Field string
	// Detail is a human-readable description of the failure.
	Detail string
	// Cause is the underlying error, if any.
	Cause error
}

UnmarshalError is a typed error returned when JSON unmarshaling fails. It includes the field context where available and wraps an optional cause.

func (*UnmarshalError) Error

func (e *UnmarshalError) Error() string

Error returns a human-readable message describing the unmarshal failure.

func (*UnmarshalError) Unwrap

func (e *UnmarshalError) Unwrap() error

Unwrap returns the underlying cause so that errors.Is and errors.As work.

type UnmarshalOptions

type UnmarshalOptions struct {
	// DiscardUnknown silently ignores unknown JSON keys when true.
	// When false, unknown keys cause an error.
	DiscardUnknown bool

	// AllowPartial allows unmarshaling a message that has missing required
	// fields. When false (the default), Unmarshal returns ErrRequiredNotSet
	// if any proto2 required field is not present after decoding. When true,
	// required field validation is skipped.
	AllowPartial bool

	// RecursionLimit sets the maximum nesting depth allowed during unmarshal.
	// A value of 0 means use the default limit of 10,000.
	RecursionLimit int

	// MaxTokenCount sets the maximum number of JSON tokens consumed during a
	// single unmarshal operation. When exceeded, unmarshal aborts with
	// ErrMaxTokenCountExceeded. A value of 0 means use the default limit of
	// 10 million. This prevents infinite-loop-without-recursion attacks.
	MaxTokenCount int

	// Resolver is an optional resolver used for resolving Any type URLs
	// during unmarshaling. Any implementation of registry.MessageResolver is
	// accepted, enabling dependency inversion: callers can supply a
	// *registry.TypeRegistry or any custom resolver. When nil,
	// registry.GlobalTypes is used.
	Resolver registry.MessageResolver
}

UnmarshalOptions configures JSON unmarshaling behavior.

fieldalignment: fields ordered for semantic clarity, not padding

func (UnmarshalOptions) Unmarshal

func (o UnmarshalOptions) Unmarshal(data []byte, msg proto.Message) error

Unmarshal deserializes JSON data into a protobuf message using the configured options. When AllowPartial is false, required fields are validated after decoding. It panics if msg is nil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL