Serialization

German camelCase and canonical JSON output, strict enum and field checks, round-trip preservation of unknown fields, the limits that make parsing untrusted payloads safe, and namespaced ZusatzAttribute.

rubo4e writes two JSON modes, keeps unknown fields through a round-trip, and offers strict checks and hardened parsing for input you do not trust.

Features: json (implies serde); the strict checks need versioned.

πŸ”—Two Output Modes

πŸ”—Side-by-Side Example

Given the same Vertrag value, the two methods produce:

to_json_german() β€” BO4E wire format (default):

{
  "_typ": "VERTRAG",
  "_version": "202607.1.0",
  "sparte": "STROM",
  "marktlokationsId": "51238696781"
}

to_json_canonical() β€” deterministic, sorted keys:

{
  "_typ": "VERTRAG",
  "_version": "202607.1.0",
  "marktlokationsId": "51238696781",
  "sparte": "STROM"
}

πŸ”—The _typ and _version metadata keys

Both are populated for you when you construct a value β€” via Default::default(), the typed builder, or ..Default::default() struct-update syntax. Both are read from the schema, so neither can drift from what the standard declares:

  • _typ is set on every BO and COM β€” each BO4E schema pins its discriminant with a JSON Schema const, and every reference implementation stamps it, nested Betrag and Adresse components included.
  • _version is set on every BO and COM to the release the schema declares.

πŸ”—_version has no v

BO4E tags its schema releases v202607.1.0, but the _version value inside a payload is 202607.1.0. Bo4eTyped::SCHEMA_VERSION is the wire spelling, so it compares directly against a _version read off a message.

Do not hardcode either string β€” a literal goes stale on the next schema series.

Deserialization never overwrites it. _version records the provenance of the data, so a payload that arrives stamped 202501.0.0 keeps that value through a round-trip, and a payload that arrives without _version stays without one. Only construction fills it in. The setter remains available if you need to re-stamp a value deliberately.

πŸ”—Decimal amounts are written as JSON strings

Betrag.wert, Preis.wert, Menge.wert and every other Decimal field serializes as a quoted string:

{ "_typ": "BETRAG", "wert": "119.00", "waehrung": "EUR" }

This matches BO4E-python (pydantic serializes Decimal as a string) and avoids f64 precision loss.

  • The published BO4E JSON Schema says "type": "number" here, so output from BO4E-python and from rubo4e both fail strict validation against BO4E's own schema β€” an upstream inconsistency.
  • Deserialization accepts both spellings. A JSON number, as go-bo4e writes it, is read too; tests/compat/ covers both.

πŸ”—β€¦but only the string spelling is exact

Serde's data model has no arbitrary-precision number, so a JSON number is already an f64 before any deserializer here is called:

WireResult
"wert": "119.00"119.00 β€” scale kept
"wert": 119.00119 β€” scale lost
"wert": "12345678901234567890.12"exact β€” 28 significant digits fit
"wert": 12345678901234567890.1212345678901234567000 β€” rounded
"wert": 9007199254740993exact β€” integers skip the f64 path

The loss happens inside the JSON parser, before this crate sees the value. No amount in the German energy market reaches 15 significant digits, so in practice only the scale changes: a relayed go-bo4e 119.00 is re-written as "119". Compare amounts rather than their spellings β€” 119 and 119.00 are the same Decimal.

Without the decimal feature the field is a String holding the lexical form, so "119.00" survives as written β€” at the cost of having no arithmetic.

πŸ”—When to Use Each Mode

ModeUse case
to_json_german()Exchange with other BO4E implementations
to_json_canonical()Content-addressed signing, payload hashing, event sourcing, diffing, caching

Both modes write BO4E's own key names. For a different key style, declare your own DTOs and map at the boundary.

to_json_canonical is not RFC 8785 (JCS). It sorts keys recursively by UTF-8 byte order (JCS uses UTF-16) and formats numbers as serde_json does. For BO4E's ASCII field names and string-encoded decimals these differences do not arise in practice.

Both are methods of the Bo4eJsonExt trait, return Result<String, serde_json::Error>, and skip None fields (no null in the output). The mode is chosen at the call site.

πŸ”—Deserialization

// Requires `json` feature
let vertrag: Vertrag = serde_json::from_str(&json_string)?;

Deserialization reads BO4E's German camelCase keys, from any of:

  • a string or byte slice (from_json_german, from_json_german_bytes)
  • an already-parsed serde_json::Value (from_json_value)

Canonical output is German JSON with sorted keys, so the same readers take it. Keys are never renamed on the way in or out: unknown fields round-trip under the names their producer chose.

πŸ”—Hardened Deserialization for Untrusted Inputs

For untrusted external payloads, use the hardened APIs with explicit limits:

use rubo4e::json::{Bo4eJsonExt, JsonParseLimits};
use rubo4e::current::Vertrag;

// `untrusted_defaults()` sets all four caps to conservative values.
let vertrag = Vertrag::from_json_german_hardened(
    &json_string,
    JsonParseLimits::untrusted_defaults(),
)?;

// Or start from a profile and narrow it (`JsonParseLimits` is `#[non_exhaustive]`).
let limits = JsonParseLimits::untrusted_defaults()
    .with_max_payload_bytes(Some(64 * 1024))
    .with_max_extension_field_count(Some(0));   // reject any unknown field
let vertrag = Vertrag::from_json_german_hardened(&json_string, limits)?;

// `unlimited()` turns every cap off β€” useful as a base when exactly one matters.
let depth_only = JsonParseLimits::unlimited().with_max_nesting_depth(Some(16));

Available hardened variants:

  • from_json_german_hardened
  • from_json_german_bytes_hardened
  • from_json_value_hardened

πŸ”—AnyBo

AnyBo dispatches on _typ, and all four budgets apply through it:

use rubo4e::current::AnyBo;

let bo = AnyBo::from_json_german_hardened(&body, JsonParseLimits::untrusted_defaults())?;
match bo {
    AnyBo::Marktlokation(m) => { /* … */ }
    AnyBo::Unknown { typ, .. } => { /* a BO type this build does not know */ }
    _ => {}
}

It buffers one intermediate serde_json::Value before dispatching, so deserialize the concrete BO type on a hot path where you know it.

πŸ”—What each limit means

LimitScopeEnforced
max_payload_byteswhole inputbefore parsing starts
max_nesting_depthwhole documentinline, during the single parse pass
max_extension_value_bytescumulative across every struct in the payloadcharged per extension field as it is parsed
max_extension_field_countper struct, at every nesting levelchecked as each struct's extension fields are read

The extension limits apply at every nesting level: extension data inside a nested COM is charged to the same budget as data on the root.

They bound what a payload retains, not what parsing allocates: #[serde(flatten)] buffers a struct's unrecognised entries before the count cap fires. max_payload_bytes is the only cap applied before parsing, so it is the one that bounds peak memory β€” set it first.

A limit that fires is a deserialization error naming the limit. The crate does not log.

πŸ”—What these limits do not bound

The object graph: [{},{},{}…] is three wire bytes per element and a full struct per element in memory, so a 1 MB body can allocate around a hundred megabytes. Size max_payload_bytes against the expanded cost, and put a concurrency limit in front of the endpoint.

πŸ”—Strict enums

Every generated enum has an Unknown catch-all, so Deserialize never fails on an unrecognised value β€” a payload from a newer schema still decodes. At an ingest boundary that must reject typos and legacy codes, parse strictly instead:

use rubo4e::{Bo4eEnum, current::Zaehlertyp};

assert_eq!(Zaehlertyp::from_wire("WASSERZAEHLER"), Ok(Zaehlertyp::Wasserzaehler));
assert!(Zaehlertyp::from_wire("LFG").is_err());       // not in this schema version
assert!(Zaehlertyp::from_wire("UNKNOWN").is_err());   // the catch-all is not a value
let z: Zaehlertyp = "WASSERZAEHLER".parse()?;         // `FromStr` is the same strict parse

for v in Zaehlertyp::iter_known() {                   // never yields Unknown
    println!("{}", v.as_wire());
}
MemberPurpose
T::VARIANTS, T::COUNT, T::iter_known()the known variants (excluding Unknown)
as_wire(), Display, AsRef<str>the canonical BO4E wire string
T::from_wire(s), s.parse()strict parse β†’ Result<T, UnknownVariant>
is_known() / is_unknown()detect the catch-all after a lenient decode
Bo4eEnumall of the above, generic over the enum type

πŸ”—Bo4eStrict β€” the whole payload at once

A lenient decode turns every unrecognised value into Unknown, anywhere in the tree. ensure_known_enums() finds them all and returns a StrictError with their paths; unknown_enum_paths() returns the paths directly:

use rubo4e::{Bo4eStrict, current::Netzlokation};

let nelo: Netzlokation = serde_json::from_value(body)?;   // never fails on enums
nelo.ensure_known_enums()?;                               // Err lists e.g. ["zaehler[1].zaehlertyp"]

It is implemented for every BO, COM, enum, and AnyBo. Unlike Bo4eTyped and Bo4eEnum it is not sealed, so your own wrapper types can implement it.

πŸ”—Round-Trip Safety (ExtensionData)

Every BO and COM struct carries an _additional field that captures any JSON keys not recognized by the struct definition:

pub struct Vertrag {
    // ... known fields ...

    #[serde(flatten)]
    #[serde(skip_serializing_if = "crate::json::ext_map_is_empty")]
    pub _additional: crate::LimitedExtensionMap,
}

A payload with fields the schema does not define survives a round-trip:

let json = r#"{
  "_typ": "VERTRAG",
  "_version": "202607.1.0",
  "_customExtension": "some-value"
}"#;

let vertrag: Vertrag = serde_json::from_str(json)?;
assert!(rubo4e::json::Bo4eExtensionData::extension_data(&vertrag)
  .contains_key("_customExtension"));

let roundtripped = vertrag.to_json_german()?;
assert!(roundtripped.contains("_customExtension"));

Top-level extension keys keep their arrival order (IndexMap). Below that a value is a serde_json::Value, whose objects are sorted, so {"b":1,"a":2} comes back as {"a":2,"b":1}; enable serde_json's preserve_order in your own Cargo.toml if that matters.

πŸ”—A decode does not validate field names

Serde ignores keys a struct does not declare; this crate keeps them. So a misspelled or renamed key does not fail a decode β€” it lands in _additional, the decode returns Ok, and the field it was meant to fill reads back as None.

let body = serde_json::json!({
    "_typ": "KOSTEN",
    "kostenbloecke": [{ "kostenblockBEZEICHNUNG": "x" }]   // misspelled
});
let kosten: Kosten = serde_json::from_value(body.clone())?;   // cannot fail
assert_eq!(kosten.kostenbloecke.unwrap()[0].kostenblockbezeichnung, None);

Decoding a hand-assembled serde_json::Value "to validate" it therefore validates nothing. has_extension_data() is shallow and answers false here, because the stray key sits one level down.

πŸ”—Bo4eExtensions β€” the recursive check

use rubo4e::json::Bo4eExtensions;

assert_eq!(kosten.extension_paths(), ["kostenbloecke[0].kostenblockBEZEICHNUNG"]);
kosten.ensure_no_extension_data()?;   // Err(UnknownFieldError { paths })

It descends through every nested BO, COM, Option and Vec. Only the top-level key of each extension entry counts β€” everything under it is opaque by design, so a vendor blob {"vendorX": {"a": 1, "b": 2}} is one finding.

Paths are dotted with bracketed array indices, like Bo4eStrict's. Extension keys come off the wire and can contain the characters the path syntax uses, so anything that is not a plain [A-Za-z0-9_] identifier is bracket-quoted: parent["a.b"].

Order is deterministic: a struct's own undefined keys first, then its children's, depth-first in field order. Within one struct they follow _additional's order β€” arrival order from text, sorted from a serde_json::Value, whose objects are a BTreeMap.

πŸ”—β€¦or make the decode itself the check

use rubo4e::json::{Bo4eJsonExt, JsonParseLimits};

let closed = JsonParseLimits::unlimited().with_max_extension_field_count(Some(0));
let kosten = Kosten::from_json_value_hardened(body, closed)?;   // Err on any stray key

from_json_value and from_json_value_hardened are the serde_json::Value counterparts of the &str readers, with the same depth and extension budgets. max_payload_bytes does not apply β€” there are no bytes left to cap β€” and is ignored rather than rejected, so one JsonParseLimits serves both paths.

πŸ”—Two questions, two calls

A payload can leave the schema in two ways, and neither check sees the other's finding:

QuestionCallTrait
Does it use a value this schema version does not define?ensure_known_enums()Bo4eStrict
Does it use a field this schema version does not define?ensure_no_extension_data()Bo4eExtensions
// `sparte` is a defined field carrying an undefined value.
let malo: Marktlokation = serde_json::from_value(json!({"sparte": "PLASMA"}))?;
assert_eq!(malo.unknown_enum_paths(), ["sparte"]);
assert!(malo.extension_paths().is_empty());

// `spartee` is an undefined field. No enum was ever reached.
let malo: Marktlokation = serde_json::from_value(json!({"spartee": "STROM"}))?;
assert_eq!(malo.extension_paths(), ["spartee"]);
assert!(malo.unknown_enum_paths().is_empty());

Rejecting an unknown value is usually right at an ingest boundary. Rejecting an unknown field usually is not β€” that is how a counterparty one schema release ahead reaches you. Run the field check on documents you produce, and inbound only where a closed field set is agreed.

πŸ”—Or do not decode to check at all

Construct the value typed, and a field rename is a compile error:

let kosten = Kosten {
    kostenbloecke: Some(vec![Kostenblock {
        kostenblockbezeichnung: Some("x".into()),
        ..Default::default()
    }]),
    ..Default::default()
};

πŸ”—ZusatzAttribut has no _typ

It is the one BO4E schema without one β€” just name and wert, and no ComTyp variant. A "_typ": "ZUSATZATTRIBUT" on one is a field BO4E does not define, and the extension check reports it.

πŸ”—Caps you cannot turn off

Every deserialization path, hardened or not, enforces:

  • MAX_EXTENSION_FIELDS (128) extension fields per struct
  • MAX_EXTENSION_KEY_LEN (256) bytes per extension key
  • DEFAULT_MAX_NESTING_DEPTH (128) levels of nesting

max_extension_field_count can tighten the first, never loosen it. Programmatic writes obey the same caps: LimitedExtensionMap::try_insert returns Err(ExtensionInsertError) rather than growing past them (replacing an existing key is always allowed), and no &mut IndexMap is exposed.

πŸ”—ZusatzAttribute and namespaces

ExtensionData above is about fields BO4E does not define β€” keys that arrived and had nowhere to go. zusatzAttribute is the opposite: the list BO4E does define, on every GeschΓ€ftsobjekt and every component, for exactly the values a sender wants to carry and the standard has no field for.

BO4E says nothing about how two systems writing into it stay apart: "id" written by two systems is one entry, and the second write wins. Nor must a receiver round-trip it, so treat a value there as a hint, not the system of record.

rubo4e::zusatz_attribut adds a namespace:key convention. ZusatzAttributeExt is available on every BO4E type that declares the field:

use rubo4e::current::SteuerbareRessource;
use rubo4e::zusatz_attribut::{Namespace, ZusatzAttributeExt};

// Each system declares its namespace once (an invalid literal is a compile error).
const HEMS: Namespace = Namespace::from_static("hems");
const MAKO: Namespace = Namespace::from_static("mako");

let mut sr = SteuerbareRessource::default();
sr.set_zusatz_attribut_in(&HEMS, "eebus-ski", "d1e2…d9e0");
sr.set_zusatz_attribut_in(&MAKO, "vorgangsnummer", "V-2026-0001");

assert_eq!(sr.zusatz_attribut_str_in(&HEMS, "eebus-ski"), Some("d1e2…d9e0"));
assert_eq!(sr.zusatz_attribut_namespaces(), ["hems", "mako"]);

The wire form is the flat BO4E name β€” {"name": "hems:eebus-ski", "wert": "…"} β€” so any BO4E reader still sees an ordinary ZusatzAttribut, and a foreign prefix you do not recognise round-trips untouched.

πŸ”—Choosing a prefix

A prefix is any well-formed name ([A-Za-z0-9_-]+, no :). There is no registry: each system declares its own β€” name your system, or the standard your data comes from.

  • Namespace::from_static is a const fn for a literal. An invalid literal panics, which in a const is a compile error, so a typo never reaches run time.
  • Namespace::new checks a prefix that arrives at run time and returns a Result.

The one prefix the crate itself uses is mabis, for the key below: a namespace is a provenance tag, and "this came from the MaBiS rules" is what a reader needs to know.

πŸ”—Typed keys, and the keys this crate defines

AttributKey<T> pins a key and its value type as one const both sides import, so they cannot disagree about what the value is:

use rubo4e::zusatz_attribut::{AttributKey, Namespace, ZusatzAttributeExt};

const HEMS: Namespace = Namespace::from_static("hems");
const LADEPUNKT: AttributKey<Ladepunkt> = AttributKey::new(HEMS, "ladepunkt");

malo.set_zusatz_attribut_key(&LADEPUNKT, &ladepunkt)?;
let read: Ladepunkt = malo.zusatz_attribut_key(&LADEPUNKT).unwrap()?;
assert_eq!(LADEPUNKT.name(), "hems:ladepunkt");

rubo4e::zusatz_attribut::well_known holds the keys this crate defines:

KeyTypeWhy BO4E has no field
mabis:zaehlpunktidentifiers::ZaehlpunktBO4E has one field for a ZΓ€hlpunktbezeichnung and assumes it is always a Messlokation; BK6-20-160 Β§1.6.2 says the ZΓ€hlpunkt (eMob) is not

A key here must qualify a BO4E field that cannot express the distinction itself. Anything else belongs in your own crate, under your own namespace, via AttributKey::new β€” see Beyond the Schema.

πŸ”—Typed values

With the json feature the value is a serde_json::Value, so anything Serialize round-trips β€” including a code list BO4E has not published and your crate has:

use rubo4e::current::TechnischeRessource;
use rubo4e::zusatz_attribut::{Namespace, ZusatzAttributeExt};

#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum Steuerungsvariante { Direktansteuerung, Ems }

const HEMS: Namespace = Namespace::from_static("hems");

let mut tr = TechnischeRessource::default();
tr.set_zusatz_attribut_as_in(&HEMS, "steuerungsvariante", &Steuerungsvariante::Ems)
    .unwrap();

let read: Steuerungsvariante = tr
    .zusatz_attribut_as_in(&HEMS, "steuerungsvariante")
    .unwrap()
    .unwrap();
assert_eq!(read, Steuerungsvariante::Ems);

πŸ”—What BO4E v202607 does not model

Two things the Β§ 14a EnWG case needs, checked against the schema this crate is generated from:

WantedIn v202607.1.0?Nearest field
Steuerungsvariante β€” Direktansteuerung vs. Steuerung ΓΌber ein EMSnonone; SteuerkanalLeistungsbeschreibung is AN_AUS / GESTUFT, which says what the channel can do, not who steers it
EEBUS SKI / identifier of the Steuerungseinrichtungnonone; SteuerbareRessource.steuerbareRessourceId is the BDEW SR-ID, a market identifier, not a device key

Both belong in a namespace. rubo4e does not define their values: a Steuerungsvariante enum here would invent a code list the market has not published. The mechanism is the crate's; the code list is yours.

Where BO4E does model something, use the field β€” a control channel's characteristic is SteuerkanalLeistungsbeschreibung, not a namespaced string.

πŸ”—Ordering and duplicates

The list is a Vec and stays one. Entries keep insertion order, and set_* replaces the first entry with that name rather than appending a second. A payload that arrived with duplicates keeps them; the getters read the first, which is what a reader that ignores the problem would also see.

remove_zusatz_attribute_in(&namespace) strips one system's entries and returns them β€” the call to make before handing a document to a partner who has no business seeing another system's internals.

πŸ”—Performance

Parsing uses serde_json. Deserialization cost is dominated by the #[serde(flatten)] buffering every struct's extension map needs, not by tokenizing, so a SIMD parser measured slower at every payload size. benches/json_perf.rs tracks the serde_json path.