Documentation
¶
Overview ¶
Example (CustomMarshaler) ¶
package main
import (
"log"
"os"
"strconv"
"github.com/wI2L/jettison"
)
type Animal int
const (
Unknown Animal = iota
Gopher
Zebra
)
func (a Animal) WriteJSON(w jettison.Writer) error {
var s string
switch a {
default:
s = "unknown"
case Gopher:
s = "gopher"
case Zebra:
s = "zebra"
}
_, err := w.WriteString(strconv.Quote(s))
return err
}
func main() {
zoo := []Animal{
Unknown,
Zebra,
Gopher,
Zebra,
Unknown,
Zebra,
Gopher,
}
b, err := jettison.Marshal(zoo)
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(b)
}
Output: ["unknown","zebra","gopher","zebra","unknown","zebra","gopher"]
Index ¶
- Constants
- Variables
- func Marshal(v interface{}) ([]byte, error)
- func MarshalTo(v interface{}, w Writer) error
- func Register(typ reflect.Type) error
- type DurationFmt
- type Encoder
- type Instruction
- type Marshaler
- type MarshalerError
- type Option
- func ByteArrayAsString() Option
- func DurationFormat(df DurationFmt) Option
- func NilMapEmpty() Option
- func NilSliceEmpty() Option
- func NoHTMLEscaping() Option
- func NoStringEscaping() Option
- func NoUTF8Coercion() Option
- func RawByteSlice() Option
- func TimeLayout(layout string) Option
- func UnixTimestamp() Option
- func UnsortedMap() Option
- type TypeMismatchError
- type UnsupportedTypeError
- type UnsupportedValueError
- type Writer
Examples ¶
Constants ¶
const ( DurationString = iota DurationMinutes DurationSeconds DurationMilliseconds DurationMicroseconds DurationNanoseconds )
Duration formats.
Variables ¶
var ErrInvalidWriter = errors.New("invalid writer")
ErrInvalidWriter is the error returned by an Encoder's Encode method when the given Writer is invalid.
Functions ¶
func Marshal ¶ added in v0.3.0
Marshal returns the JSON encoding of v. It uses a pre-compiled encoder from the package's cache, or create and store one on the fly.
Example ¶
package main
import (
"log"
"os"
"github.com/wI2L/jettison"
)
func main() {
type X struct {
A string `json:"a"`
B int64 `json:"b"`
C []string `json:"colors"`
}
x := X{
A: "Loreum",
B: -42,
C: []string{"blue", "green", "purple"},
}
b, err := jettison.Marshal(&x)
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(b)
}
Output: {"a":"Loreum","b":-42,"colors":["blue","green","purple"]}
func MarshalTo ¶ added in v0.3.0
MarshalTo writes the JSON encoding of v to w. It uses a pre-compiled encoder from the package's cache, or create and store one on the fly.
Example ¶
package main
import (
"bytes"
"log"
"os"
"github.com/wI2L/jettison"
)
func main() {
type X struct {
A bool `json:"a"`
B uint32 `json:"b"`
C map[string]string `json:"users"`
}
x := X{
A: true,
B: 42,
C: map[string]string{
"bob": "admin",
"jerry": "user",
},
}
var buf bytes.Buffer
err := jettison.MarshalTo(&x, &buf)
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(buf.Bytes())
}
Output: {"a":true,"b":42,"users":{"bob":"admin","jerry":"user"}}
Types ¶
type DurationFmt ¶
type DurationFmt int
DurationFmt represents the format used to encode a time.Duration value.
func (DurationFmt) String ¶
func (df DurationFmt) String() string
String implements the fmt.Stringer interface.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder writes the JSON values of a specific type using a set of instructions compiled when the encoder is instantiated.
func NewEncoder ¶
NewEncoder returns a new encoder that can marshal the values of the given type. The Encoder can be explicitly initialized by calling its Compile method, otherwise the operation is done on first call to Marshal.
func (*Encoder) Compile ¶
Compile generates the encoder's instructions. Calling this method more than once is a noop.
func (*Encoder) Encode ¶
Encode writes the JSON encoding of i to w.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"reflect"
"github.com/wI2L/jettison"
)
func main() {
type X struct {
M map[string]int
S []int
}
x := X{}
enc, err := jettison.NewEncoder(reflect.TypeOf(x))
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if err := enc.Encode(&x, &buf); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf.String())
buf.Reset()
if err := enc.Encode(&x, &buf,
jettison.NilMapEmpty(),
jettison.NilSliceEmpty(),
); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf.String())
}
Output: {"M":null,"S":null} {"M":{},"S":[]}
type Instruction ¶
Instruction represents a function that writes the JSON representation of a value to a stream.
type Marshaler ¶ added in v0.4.0
Marshaler is a variant of the json.Marshaler interface, implemented by types that can write a valid JSON representation of themselves to a Writer. If a type implements both interfaces, Jettison will use its own interface in priority.
type MarshalerError ¶
MarshalerError represents an error from calling a MarshalJSON or MarshalText method.
func (*MarshalerError) Error ¶
func (e *MarshalerError) Error() string
Error implements the builtin error interface.
func (*MarshalerError) Unwrap ¶ added in v0.3.0
func (e *MarshalerError) Unwrap() error
Unwrap returns the wrapped error. This doesn't implement a public interface, but allow to use the errors.Unwrap function released in Go 1.13 with a MarshalerError.
type Option ¶
type Option func(*encodeOpts)
Option overrides a particular behavior of an encoder
func ByteArrayAsString ¶
func ByteArrayAsString() Option
ByteArrayAsString encodes byte arrays as raw JSON strings.
func DurationFormat ¶
func DurationFormat(df DurationFmt) Option
DurationFormat sets the format used to encode time.Duration values.
func NilMapEmpty ¶
func NilMapEmpty() Option
NilMapEmpty encodes nil Go maps as empty JSON objects, rather than null.
func NilSliceEmpty ¶
func NilSliceEmpty() Option
NilSliceEmpty encodes nil Go slices as empty JSON arrays, rather than null.
func NoHTMLEscaping ¶ added in v0.3.1
func NoHTMLEscaping() Option
NoHTMLEscaping disables the escaping of HTML characters when encoding JSON strings.
func NoUTF8Coercion ¶ added in v0.3.1
func NoUTF8Coercion() Option
NoUTF8Coercion disables UTF-8 coercion when encoding JSON strings.
func RawByteSlice ¶ added in v0.4.0
func RawByteSlice() Option
RawByteSlice disables the default behavior that encodes byte slices as base64-encoded strings.
func TimeLayout ¶
TimeLayout sets the time layout used to encode time.Time values.
func UnixTimestamp ¶
func UnixTimestamp() Option
UnixTimestamp configures the encoder to encode time.Time values as Unix timestamps. This option has precedence over any time layout.
type TypeMismatchError ¶ added in v0.3.0
TypeMismatchError is the error returned by an Encoder's Encode method whhen the type of the input value does not match the type for which the encoder was compiled.
func (*TypeMismatchError) Error ¶ added in v0.3.0
func (e *TypeMismatchError) Error() string
Error implements the builtin error interface.
type UnsupportedTypeError ¶
UnsupportedTypeError is the error returned by an Encoder's Encode method when attempting to encode an unsupported value type.
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
Error implements the bultin error interface.
type UnsupportedValueError ¶
type UnsupportedValueError struct {
Str string
}
UnsupportedValueError is the error returned by an Encoder's Encode method when attempting to encode an unsupported value.
func (*UnsupportedValueError) Error ¶
func (e *UnsupportedValueError) Error() string
Error implements the builtin error interface.
type Writer ¶
type Writer interface {
io.Writer
io.StringWriter
io.ByteWriter
}
Writer is an interface that groups the io.Writer, io.StringWriter and io.ByteWriter interfaces.
