Expand description
A dependency-free JSON parser and serializer.
You describe a struct and implement New,
FromJSON and ToJSON for it; the trait bodies call the module’s helpers
for each property. Nested objects and arrays are supported. It is not a
validator or formatter, but invalid input is an error, not a panic.
Submodules: object, [array], property; examples live in their
tests/example_* modules (objects, nested objects, arrays of every scalar
type, arrays of objects).
With the serde feature, Json<T> extracts a Deserialize type
from a request body and turns a Serialize type into an application/json
response — use that unless you want the explicit, macro-free mapping.
§FAQ
- Line endings. The parser doesn’t care about
\nvs\r\n;to_json_stringwrites\r\n, so compare against\r\ntext in tests. - No pretty-printing.
to_json_stringadds line breaks but doesn’t indent nested values. - Why
New? Parsing an array has to create instances of your struct. - Mixed-type arrays (
[1, true, "x"], tuples) don’t map to one struct type; model them as an array of objects, or split the raw array withRawUnprocessedJSONArray::split_into_vector_of_stringsand parse each item. - Numbers are
i128andf64(JSON has one number type); cast in yourFromJSONif you need smaller types.f64has the usual binary rounding (4356.257reads back as4356.2569999999996) — store money as integer cents, or round when formatting. - Enums have no JSON form: keep a string/integer property and map it to
your enum in
FromJSON/ToJSON.
Modules§
- array
- JSON arrays: parse
[ … ]intoVec<T>and back. For a struct type, implementNew,FromJSONandToJSON, then callfrom_json_list/to_json_list. Scalar arrays (integers, floats, strings, booleans, nulls) have their own helpers in the submodules. - object
- JSON objects: parse
{ … }into a struct (parse_json) and serialize it back (to_json_string) through theFromJSON/ToJSONtraits. Seetests/example_multi_nested_object. - property
- One JSON property:
JSONProperty(name and type) andJSONValue(the parsed value — string, bool, object, array,i128,f64or null).