Package Usage: go: github.com/fjl/gencodec
Command gencodec generates marshaling methods for struct types.
When gencodec is invoked on a directory and type name, it creates a Go source file
containing JSON, YAML and TOML marshaling methods for the type. The generated methods add
features which the standard json package cannot offer.
The gencodec:"required" tag can be used to generate a presence check for the field.
The generated unmarshaling method returns an error if a required field is missing.
Other struct tags are carried over as is. The "json", "yaml", "toml" tags can be used to
rename a field when marshaling.
Example:
An invocation of gencodec can specify an additional 'field override' struct from which
marshaling type replacements are taken. If the override struct contains a field whose name
matches the original type, the generated marshaling methods will use the overridden type
and convert to and from the original field type. If the override struct contains a field F
of type T, which does not exist in the original type, and the original type has a method
named F with no arguments and return type assignable to T, the method is called by Marshal*.
If there is a matching method F but the return type or arguments are unsuitable, an error
is raised.
In this example, the specialString type implements json.Unmarshaler to enforce additional
parsing rules. When json.Unmarshal is used with type foo, the specialString unmarshaler
will be used to parse the value of SpecialField. The result of foo.Func() is added to the
result on marshaling under the key `id`. If the input on unmarshal contains a key `id` this
field is ignored.
Field types in the override struct must be trivially convertible to the original field
type. gencodec's definition of 'convertible' is less restrictive than the usual rules
defined in the Go language specification.
The following conversions are supported:
If the fields are directly assignable, no conversion is emitted. If the fields are
convertible according to Go language rules, a simple conversion is emitted. Example input
code:
The generated code will contain:
If the fields are of map or slice type and the element (and key) types are convertible, a
simple loop is emitted. Example input code:
The generated code is similar to this snippet:
Conversions between slices and arrays are supported. Example input code:
The generated code is similar to this snippet:
4 versions
Latest release: about 2 years ago
608 dependent packages
View more package details: https://packages.ecosystem.code.gouv.fr/registries/proxy.golang.org/packages/github.com/fjl/gencodec