macro_rules! json_struct {
($name:ident { $($field:ident $(: $key:literal)?),* $(,)? }) => { ... };
($name:ident < $lt:lifetime > { $($field:ident $(: $key:literal)?),* $(,)? }) => { ... };
}Expand description
Implements ToJson and FromJson
for a struct whose fields map one to one onto object members.
The macro writes exactly the hand implementation the
FromJson docs show, nothing more: each field listed
is a member, keyed by the field’s name or by the string given after a
colon (new_text: "newText"). It is a macro_rules! macro over the list
you write, not a derive: no attribute, no reflection, and every key is in
your source.
- Reading: members in any order; unknown members skipped (and
validated); a repeated field refused
(
DecodeErrorKind::DuplicateField); a missing field refused (DecodeErrorKind::MissingField) unless its type allows absence: anOption<T>field reads asNone, aNullable<T>asAbsent. - Writing: members in the order listed; an
Option<T>field that isNone(or aNullablethat isAbsent) is left out, which is TypeScript’skey?: Tas LSP and MCP use it.
For a struct with a lifetime (to borrow strings from the input), name it:
json_struct!(Name<'a> { ... }). For anything else (renamed variants,
defaults, validation, enums), write the impls by hand.
§Examples
use std::borrow::Cow;
use jsonx_lib::json_struct;
#[derive(Debug, PartialEq)]
struct Position { line: u32, character: u32 }
json_struct!(Position { line, character });
#[derive(Debug, PartialEq)]
struct TextEdit<'a> { range: [Position; 2], new_text: Cow<'a, str>, label: Option<String> }
json_struct!(TextEdit<'a> { range, new_text: "newText", label });
let text = r#"{"newText": "x", "range": [{"line": 1, "character": 0}, {"line": 1, "character": 3}]}"#;
let edit: TextEdit = jsonx_lib::from_str(text)?;
assert_eq!(edit.new_text, "x");
assert_eq!(edit.label, None);
assert_eq!(
jsonx_lib::to_string(&edit),
r#"{"range":[{"line":1,"character":0},{"line":1,"character":3}],"newText":"x"}"#
);