
Understand it
JSON describes data exchange, while your application model describes valid state. Deserialize into a small transport structure, then convert it into a domain value whose constructor enforces the rules. A syntactically valid JSON object can still contain a blank display name, a negative quantity, or a count larger than the application supports. Do not spread those checks across every consumer.
Choose an evolution policy. Serde derive normally ignores unknown fields unless configured with deny_unknown_fields. This explicit visitor rejects unknown and duplicate fields itself. Neither choice is universally safer: rejecting surprises is useful for a tightly controlled command, while forward-compatible clients may need to tolerate new fields. Document the decision, and use an explicit format version when a later change would reinterpret an existing field.
Compare decoded meaning in a round-trip test rather than relying on object-key order or pretty-print whitespace. Avoid printing full input documents into error logs when they may contain private data. Limit input size before decoding untrusted text, and distinguish a parse error from a domain validation error. The lab in the previous lesson stays dependency-free; this lesson shows how to replace its intentionally restricted transport format with an established serialization library.
The visitor checks duplicate, missing and unknown fields while Serde checks each field type. A u32 rejects negative and overflowing counts. The separate decode function bounds input size and rejects blank names. Main asserts all of those failures as well as a Unicode round-trip; a successful JSON parse alone is not evidence of domain validity.
Local Cargo profile: open the supplied project in Crabrix or the browser Playground. Explicitly prepare its pinned Cargo packages once on each device, then Run and Debug compile and execute on that device without a backend. The project includes Cargo.lock. The lesson question remains the completion exercise; running an unchanged demonstration does not prove a separate programming challenge. This starter uses real serde 1.0.229 and serde_json 1.0.151 with explicit Serialize and Deserialize implementations. That keeps the typed round-trip, strict field policy and domain validation portable without a procedural macro. Derive can generate the same traits on a toolchain with qualified macro support; this lab does not require the experimental macro compiler.
Read the code
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{Error, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use std::fmt;
#[derive(Debug, PartialEq)]
struct Record { name: String, count: u32 }
// Explicit Serde traits keep this example portable to the released WASI
// compiler. They use the real serde/serde_json crates, without derive macros.
impl Serialize for Record {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut fields = s.serialize_struct("Record", 2)?;
fields.serialize_field("name", &self.name)?;
fields.serialize_field("count", &self.count)?;
fields.end()
}
}
impl<'de> Deserialize<'de> for Record {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct RecordVisitor;
impl<'de> Visitor<'de> for RecordVisitor {
type Value = Record;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a record with name and count")
}
fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Record, M::Error> {
let (mut name, mut count) = (None, None);
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"name" => {
if name.is_some() { return Err(M::Error::duplicate_field("name")); }
name = Some(map.next_value()?);
}
"count" => {
if count.is_some() { return Err(M::Error::duplicate_field("count")); }
count = Some(map.next_value()?);
}
_ => return Err(M::Error::unknown_field(&key, &["name", "count"])),
}
}
Ok(Record {
name: name.ok_or_else(|| M::Error::missing_field("name"))?,
count: count.ok_or_else(|| M::Error::missing_field("count"))?,
})
}
}
d.deserialize_struct("Record", &["name", "count"], RecordVisitor)
}
}
fn decode(text: &str) -> Result<Record, Box<dyn std::error::Error>> {
if text.len() > 4096 { return Err("record is too large".into()); }
let row: Record = serde_json::from_str(text)?;
if row.name.trim().is_empty() { return Err("blank name".into()); }
Ok(row)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let row = decode(r#"{"name":"crab 🦀","count":3}"#)?;
let encoded = serde_json::to_string(&row)?;
assert_eq!(decode(&encoded)?, row);
for bad in [r#"{"name":" ","count":3}"#, r#"{"name":"crab"}"#,
r#"{"name":"crab","count":-1}"#, r#"{"name":"crab","count":4294967296}"#,
r#"{"name":"crab","count":3,"extra":true}"#,
r#"{"name":"crab","name":"other","count":3}"#, "{"] {
assert!(decode(bad).is_err());
}
assert!(decode(&"x".repeat(4097)).is_err());
println!("Serde round-trip and validation: ok");
Ok(())
}
Real Serde traits: strict typed decoding, separate domain validation and a semantic JSON round-trip.
Try it
In Crabrix or the web Playground, run the example with the two declared dependencies. Add a domain constructor, then test blank names, missing fields, unknown fields, and an out-of-range count. Open the supplied local Cargo project, prepare packages, then Run or Debug it. Change inputs and examine the assertions. Answer the lesson question separately.
What success looks like: A String is structurally valid even when empty. Validate domain invariants after decoding.
Check your understanding
Does deriving Deserialize guarantee that name is nonblank?
Reveal the answer
- Yes, all String fields are nonblank
- No, the application must validate that invariant
- Only if JSON keys are sorted
A String is structurally valid even when empty. Validate domain invariants after decoding.
Go deeper
Common misconception: Valid JSON is already a valid business record.
The format and type checker do not know application-specific constraints.
- Decode: Turn JSON into a transport structure and preserve a useful error.
- Validate: Construct domain state only after checking its invariants.
- Encode: Round-trip meaning and document the schema's evolution policy.
Transfer challenge: Design a versioned settings format that accepts an older document without silently changing the meaning of a stored field.
Connections
- Validate Data Records: A bounded text format with precise errors