pub trait FromRawJsonValue<'text>: Sized {
// Required method
fn from_raw_json_value(
value: RawJsonValue<'text, '_>,
) -> Result<Self, JsonParseError>;
}Expand description
Converts a raw JSON value to a specific Rust type.
This trait allows for extracting typed values from untyped RawJsonValue
representations, performing necessary type checking and conversions.
Implementing this trait enables a type to be deserialized from JSON data.
Once a type implements FromRawJsonValue, you can use Json to parse
JSON text to that type through Rust’s standard FromStr trait.
§Examples
Parse a JSON array to a vector of integers:
use nojson::{Json, RawJson, JsonParseError};
// Parse a JSON text via `str::parse()`.
let numbers: Json<[u32; 3]> = "[1, 2, 3]".parse()?;
assert_eq!(numbers.0, [1, 2, 3]);
// Alternatively, you can use `RawJson::parse()`,
// which offers a more flexible approach for converting JSON values and
// generating context-rich error messages.
let raw = RawJson::parse("[1, 2, 3]")?;
// For types that implement the `FromRawJsonValue` trait,
// the `RawJsonValue::try_to()` method can be used for conversion.
let numbers: [u32; 3] = raw.value().try_to()?;
assert_eq!(numbers, [1, 2, 3]);Parse a JSON object to a custom struct (requires implementing FromRawJsonValue for your struct):
use nojson::{Json, RawJsonValue, JsonParseError, FromRawJsonValue};
struct Person {
name: String,
age: u32,
}
impl<'text> FromRawJsonValue<'text> for Person {
fn from_raw_json_value(value: RawJsonValue<'text, '_>) -> Result<Self, JsonParseError> {
let ([name, age], []) = value.to_fixed_object(["name","age"],[])?;
Ok(Person {
name: name.try_to()?,
age: age.try_to()?,
})
}
}
let person: Json<Person> = r#"{"name":"Alice","age":30}"#.parse()?;
assert_eq!(person.0.name, "Alice");
assert_eq!(person.0.age, 30);Parse a rational number represented as a JSON string:
use nojson::{Json, RawJsonValue, JsonParseError, FromRawJsonValue};
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Rational {
numerator: i32,
denominator: i32,
}
impl<'text> FromRawJsonValue<'text> for Rational {
fn from_raw_json_value(value: RawJsonValue<'text, '_>) -> Result<Self, JsonParseError> {
// Get the raw string content of the JSON value.
let fraction_str = value.to_unquoted_string_str()?;
// Split by the '/' character and parse components.
let parts: Vec<&str> = fraction_str.split('/').collect();
if parts.len() != 2 {
return Err(JsonParseError::invalid_value(value, "Expected format 'numerator/denominator'"));
}
let numerator = parts[0].parse()
.map_err(|_| JsonParseError::invalid_value(value, "Invalid numerator"))?;
let denominator = parts[1].parse()
.map_err(|_| JsonParseError::invalid_value(value, "Invalid denominator"))?;
if denominator == 0 {
return Err(JsonParseError::invalid_value(value, "Denominator cannot be zero"));
}
Ok(Rational { numerator, denominator })
}
}
let fraction: Json<Rational> = r#""3/4""#.parse()?;
assert_eq!(fraction.0, Rational { numerator: 3, denominator: 4 });Required Methods§
Sourcefn from_raw_json_value(
value: RawJsonValue<'text, '_>,
) -> Result<Self, JsonParseError>
fn from_raw_json_value( value: RawJsonValue<'text, '_>, ) -> Result<Self, JsonParseError>
Attempts to convert a raw JSON value to this type.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.