pub struct Json<T> { /* private fields */ }json only.Expand description
A lazy JSON parser that defers deserialization until requested.
Json<T> holds JSON data in its raw form and only parses it when you call
read or read_owned.
The type supports two parsing modes:
-
Lifetime-aware parsing via
read: Can borrow from the buffer when possible. Multiple read calls can be made, and the returned value, if it contains a lifetime, is tied to the lifetime of the parser. -
Owned parsing via
read_owned: For types that own their data, the parser consumes itself and returns an owned deserialized value.
See the HttpBody::into_json_ref and
HttpBody::into_json methods for more details and
examples on how to use this type.
Implementations§
Source§impl<'a, T: Deserialize<'a>> Json<T>
impl<'a, T: Deserialize<'a>> Json<T>
Sourcepub fn read(&'a mut self) -> Result<T, JsonError>
pub fn read(&'a mut self) -> Result<T, JsonError>
Parses the JSON data using lifetime-aware deserialization.
This method can deserialize both borrowed and owned data. When deserializing strings and byte arrays, it can borrow directly from the JSON buffer for better performance. For other types like numbers, Boolean values, and owned containers, it creates new values as needed.
The returned value is tied to the lifetime of this parser, but that doesn’t mean all fields must be borrowed - you can mix borrowed and owned fields.
§Examples
#[derive(Deserialize)]
struct Person<'a> {
#[serde(borrow)] // You need to tell serde to borrow this field
name: Cow<'a, str>,
age: u32,
}
fn handle_json<'a>(json: &'a mut Json<Person<'a>>) -> Result<(), HttpError> {
let person: Person = json.read()?;
Ok(())
}§Errors
Returns an error if the JSON deserialization fails.
Source§impl<T: DeserializeOwned> Json<T>
impl<T: DeserializeOwned> Json<T>
Sourcepub fn read_owned(self) -> Result<T, JsonError>
pub fn read_owned(self) -> Result<T, JsonError>
Parses the JSON data into owned values, consuming the parser.
This method creates owned strings and collections, making the returned value independent of the parser lifetime. Use this when you need to store the parsed data beyond the scope of the JSON parser.
This method consumes the parser, so you can only call it once.
§Examples
#[derive(Deserialize)]
struct Person {
name: String, // Owned string
age: u32,
}
fn handle_json(json: Json<Person>) -> Result<(), HttpError> {
let person: Person = json.read_owned()?; // Consumes the parser
Ok(())
}§Errors
Returns an error if the JSON deserialization fails.