Ниже показан английский оригинал.
JSON
JsonCodec reads and writes JSON through serde_json; it is the default codec, on with the json feature.
The json feature is a default feature of the crate.
While it is on, DefaultCodec is JsonCodec, so a handler mounted with no codec named decodes JSON, and a reply is encoded in JSON.
A message type derives serde::Deserialize; a type the handler publishes derives Serialize as well.
The media type is application/json, and the generated AsyncAPI document reports it for each message.
A payload that is not JSON, or JSON of another shape, is a decode failure, settled by the subscriber's failure policy.
To name JSON where another codec is the scope's, mount through a router or a registration that names it, as on Codecs.
On a device without the standard library (target_os = "none") the type and the wire format are the same.
Decoding stays serde_json, on the allocator, and allocates only scratch for a string with escapes.
Encoding goes through serde-json-slice, which writes the bytes serde_json writes straight into the encode buffer, with no allocation of its own.
The buffer grows as a BytesMut does, so a message is not cut at a size.
The same service source builds with either.
Example
The example builds with JSON as the only codec:
cargo test --example codec_json --no-default-features --features tokio,testing,macros,memory,json
- Macros
- Manual
#[subscriber("orders")]
async fn bill(order: &Order) -> HandlerOutcome {
tracing::info!(order.id, "billed");
HandlerOutcome::ack()
}
fn app() -> impl App {
// No codec named anywhere: the handler decodes with the default codec, JSON.
RustStream::new(AppInfo::new("billing", "0.1.0"))
.with_broker(MemoryBroker::new(), |b| b.include(bill))
}
struct Bill;
impl Handle<Order> for Bill {
fn handle(
&self,
order: &Order,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
tracing::info!(order.id, "billed");
ready(Ok(()))
}
}
fn app() -> impl App {
// No codec named anywhere: the registration decodes with the default codec, JSON.
RustStream::new(AppInfo::new("billing", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(subscriber("orders", Bill).build())
})
}