Skip to main content

Jsony

Derive Macro Jsony 

Source
#[derive(Jsony)]
{
    // Attributes available to this derive:
    #[jsony]
}
Expand description

Unified derive macro for implementing various conversion traits

Configured with attributes in the form #[jsony(...)] on containers, variants, and fields.

The traits/methods to derive are specified via container attributes. The currently supported traits/methods are:

  • ToJson
  • FromJson
  • ToBinary
  • FromBinary
  • FromStr
  • ToStr (inherent method)

The rest of the attributes are described in the following tables. Note that some attributes apply only to certain traits.

§Container Attributes

These are jsony attributes that appear above a struct or enum.

FormatSupported TraitsDescription
content = "..."JsonField containing the data content of enum.
FlattenableFromJsonAllows type to use #[jsony(flatten)] in FromJson.
ignore_tag_adjacent_fieldsJsonIgnore extra fields in externally tagged enum object
rename_all = "..."AllRenames variants and fields not explicitly renamed.
rename_all_fields = "..."AllOn enums, overrides rename_all for fields in struct variants.
tag = "..."JsonField containing the enum variant.
transparentAllTraits delegate to the single inner type.
untaggedJsonOnly data content of an enum is stored.
version [= N]BinaryEnable binary versioning. Sets current version (default 0 or largest field version).
version = M..BinaryCurrent version is M or largest field version, error on attempt to decode versions less then M
version = M..=NBinaryCurrent version is N, error on attempt to decode versions less then M
zerocopyBinaryEnables zerocopy support and asserts requirements are met.

§Enum Variant Attributes

These are jsony attributes that appear above a variant in an enum.

FormatSupported TraitsDescription
rename = "..."JsonUse provided string as variant name.
rename_all = "..."AllRenames fields within this variant. Overrides container rename_all_fields.
otherFromJsonVariant to use if given an unknown variant

§Field Attributes

These are jsony attributes that appear above a field inside a struct or enum variant.

FormatSupported TraitsDescription
alias = "..."FromJsonUse provided string as a alternative field name when decoding.
default [= ...]FromUse Default::default() or provided expression if field is missing.
flattenJsonFlatten the contents of the field into the container it is defined in.
rename = "..."JsonUse provided string as field name.
validate = ...FromProvided a fn(&T) -> Result<(), String> function fails deserialization if Err(())
version = NBinaryField added in version N. Needs default when reading older versions.
via = ...AllImplement conversion through provided trait.
skipAllOmit field while serializing, use default value when deserializing.
skip_if = ...ToJsonOmit field while serializing if provided function returns true.
with = ...AllUse methods from specified module instead of trait. read more

§Format Aliases

In the container attributes to specify the traits to derive and on the prefix of other attributes to specify which traits that attribute should apply to, you can use the following aliases to specify multiple traits at once:

AliasTraits IncludedDescription
ToToJson, ToBinaryAll traits converting a Rust type to serialized format
FromFromJson, FromBinaryAll traits converting from a serialized format to a Rust type
BinaryToBinary, FromBinaryAll Binary encoding traits
JsonToJson, FromJsonAll JSON encoding traits
StrToStr, FromStrEnum between string slice converting function

As more formats are added, these aliases may expand. If an attribute only supports a subset of traits specified by the set, then the rest are ignored. If the set specified is disjoint, an error will be raised. For example:

#[jsony(To flatten)] is the same as #[jsony(ToJson flatten)] as ToBinary does not support flatten. Whereas #[jsony(Binary flatten)] is a compile-time error since flatten is not supported by either ToBinary nor FromBinary.

§Detailed Field Attributes Descriptions

§#[jsony(with = ...)] on fields

Uses the functions from the provided module path when a encoding/decoding trait method would normally be used.

The function corresponds to the save methods of each trait (omitting the __jsony suffix if present).

TraitFunction
ToJsonfn encode_json(value: &bool, output: &mut TextWriter)
FromJsonfn decode_json<'a>(parser: &mut jsony::parser::Parser<'a>) -> Result<bool, &'static DecodeError>
ToBinaryfn encode_binary(value: &bool, output: &mut BytesWriter)
FromBinaryfn decode_binary(decoder: &mut jsony::binary::Decoder<'_>) -> bool
§Example of with attribute
mod bool_as_int {
    use jsony::{
        json::DecodeError, BytesWriter, FromBinary, FromJson, TextWriter, ToBinary, ToJson,
    };
    pub fn encode_json(value: &bool, output: &mut TextWriter) {
        (*value as u32).encode_json__jsony(output);
    }
    pub fn decode_json(parser: &mut jsony::parser::Parser<'_>) -> Result<bool, &'static DecodeError> {
        Ok(<u32>::decode_json(parser)? != 0)
    }
    pub fn encode_binary(value: &bool, output: &mut BytesWriter) {
        (*value as u32).encode_binary(output)
    }
    pub fn decode_binary(decoder: &mut jsony::binary::Decoder<'_>) -> bool {
        u32::decode_binary(decoder) != 0
    }
}

#[derive(Jsony)]
#[jsony(Binary, Json)]
struct Example {
    #[jsony(with = bool_as_int)]
    value: bool
}

Note: The functions in the with module can be generic.

§#[jsony(skip)]

Omit the field while serializing and use the default value when deserializing. If no default value is specified with default then Default::default() is used.

skip is useful when you need a field on the rust side that isn’t present in the serialized data format.

§Detailed Container Attributes Descriptions

§#[jsony(transparent)]

Must be used on a struct containing a single field. If #[repr(transparent)] is also specified, a more efficient implementation may be used that ensures delegations become zero-cost.

§#[jsony(rename_all = "...")]

The possible values are “lowercase”, “UPPERCASE”, “PascalCase”, “camelCase”, “snake_case”, “SCREAMING_SNAKE_CASE”, “kebab-case”, “SCREAMING-KEBAB-CASE”.

On a struct, this renames all fields. On an enum, this renames both variant names and field names within struct variants. Use rename_all_fields to apply a different rule to fields than to variant names.

§#[jsony(rename_all_fields = "...")]

Accepts the same values as rename_all. Only meaningful on enums: overrides rename_all for fields in struct variants while leaving variant names unaffected.

Per-variant #[jsony(rename_all = "...")] on an enum variant overrides both the container rename_all and rename_all_fields for that variant’s fields.

§#[jsony(validate = ...)]

Requires of a function of the form fn(&Self) -> Result<(), String> that will be called during deserialization, on the deserialized value. If the function returns Err(_), the deserialization will fail with the provided error message.

The jsony::require! macro is provided to aid in defining the logical inline.

§Binary Versioning (#[jsony(version = ...)])

The version attribute on containers (struct/enum) enables versioning for ToBinary and FromBinary.

  • ToBinary: The current version is written as a prefix and is either specified explicitly via the container attribute or inferred via the largest field version.
  • FromBinary:
    • By default (version = N), all versions below the current version will attempted to be decoded, using the attribute default or Default::default() for absent fields of older versions.
    • When using a range a minimum version that will reject small versions.
  • Field: Use #[jsony(version = N)] on fields added in a specific

This system allows newer code to read older data by providing defaults for new fields, and helps older code detect and reject data from newer, unknown versions. Breaking changes can be managed by incrementing the minimum required version (e.g., changing version = 1.. to version = 2..).

#[derive(Jsony, PartialEq, Debug)]
#[jsony(Binary, version)] // Current version 0
struct RecordV0 { value: u32 }

#[derive(Jsony, PartialEq, Debug)]
#[jsony(Binary, version)] // Current version 1
struct RecordV1<'a> {
    value: u32,
    #[jsony(version = 1, default = "N/A")] // Added in V1
    name: &'a str,
}

let bin_v0 = to_binary(&RecordV0 { value: 10 });
assert_eq!(
    from_binary::<RecordV1>(&bin_v0).unwrap(),
    RecordV1 { value: 10, name: "N/A"}
);
§#[jsony(zerocopy)]

Enables zero-copy optimizations for FromBinary and ToBinary implementations. This allows borrowing the data directly from the input byte slice, improving performance.

Requirements:

  • The struct must be #[repr(C)] or #[repr(transparent)].
  • The struct must be Plain Old Data (POD) – having a defined layout with no padding, suitable for direct memory interpretation.

Safety:

Using this attribute is safe. The necessary POD constraints are checked at compile time via const assertions. If the requirements are not met, a compile-time error occurs. This avoids the need for unsafe code often associated with manual FromBinary::POD = true implementations.

Alignment and Slices:

Deserializing slices like &[Self] requires the input data to have the correct alignment for Self. If alignment cannot be guaranteed, using Cow<'_, [Self]> is recommended. Cow will borrow if possible, or create an owned copy if the input alignment is insufficient.

Limitations:

  • Big Endian: As of jsony v0.1, zero-copy support on Big Endian systems is limited to types of size_of::<T>() == 1. Future versions may expand this.
§#[jsony(skip_if = ...)]

Omit the field if the provided predicate function return true. The predicate function can be specified by a path or inline using closure syntax. The predicate function will provided the current field value via reference.

#[derive(Jsony)]
#[jsony(ToString)]
struct Example {
    #[jsony(skip_if = str::is_empty)]
    value: String,
    #[jsony(skip_if = |s| s == u32::MAX)]
    sentinel: u32
}
§Default enum representation for JSON
EnumJSON for Example::AlphaJSON for Example::Beta
#[derive(Jsony)]
enum Example {
    Alpha {
        field: bool
    },
    Beta
}
{
    "Alpha": {
        "field": true
    }
}
"Beta"
§Enum with #[jsony(tag = "...")]

May not be used with untagged.

EnumJSON for Example::AlphaJSON for Example::Beta
#[derive(Jsony)]
#[jsony(tag = "kind")]
enum Example {
    Alpha {
        field: bool
    },
    Beta
}
{
    "kind": "Alpha",
    "field": true
}
{
    "kind": "Beta"
}
§Enum with #[jsony(tag = "...", content = "...")]

May not be used with untagged. Note that the content attribute content must be used with tag.

EnumJSON for Example::AlphaJSON for Example::Beta
#[derive(Jsony)]
#[jsony(tag = "kind", content = "data")]
enum Example {
    Alpha {
        field: bool
    },
    Beta
}
{
    "tag": "Alpha",
    "data": {
        "field": true
    }
}
{
    "tag": "Beta"
}
§Enum with #[jsony(untagged)]
EnumJSON for Example::AlphaJSON for Example::Beta
#[derive(Jsony)]
#[jsony(untagged)]
enum Example {
    Variant {
        field: bool
    }
}
{
    "field": true
}

Not Supported

§Enum Conversion Helpers

The Jsony derive can also automatically implement common conversions for enums. Not only is the same proc-macro expansion innovcation and parsing of the derive target shared, but the implementation can be as well. For instance an Enum with #[jsony(FromJson, FromStr)] may have the FromJson impl internally call FromStr.

Example:

#[derive(Jsony, PartialEq, Debug)]
#[jsony(ToStr, FromStr, rename_all = "kebab-case")]
enum Mode {
    Slow,
    Fast,
    TurboMax,
}

assert_eq!(Mode::TurboMax.to_str(), "turbo-max");
assert_eq!("slow".parse::<Mode>(), Ok(Mode::Slow));
assert!("zzz".parse::<Mode>().is_err());
  • FromStr will implement [std::str::FromStr] (often invoked via str::parse as seen in the example).
  • ToStr will implement a inherent method on the enum with the following signature:
pub fn to_str(&self) -> &'static str;

Rename attributes on variants will be respected for these conversion.

§Why a single unified derive macro?

By convention, derive macros are typically named after the trait they implement. Jsony breaks this convention to reduce compilation time as the unified approach:

  1. Avoids the overhead of multiple derive macro invocations.
  2. Needs to parse the input only once.
  3. Allows traits to share code, as the macro knows the full set being implemented.

These optimizations are particularly useful for Jsony because:

  • The derive macros are already extremely efficient, such that invocation overhead is measurable.
  • Jsony’s approach of having specialized traits for different formats means users often want to implement many traits.