When using serde-json-core::from_str, deserialization can fail due to various reasons. The library provides specific error variants in crate::de::Error to help identify the cause of failure.
Common error scenarios include:
TrailingCharacters: The JSON string contains more data after the valid JSON object has been parsed (e.g., [10, 20, 30] when expecting a tuple of 2).CustomError: A general error returned by the deserializer (e.g., when a tuple struct has the wrong number of elements).ExpectedSomeValue: The JSON structure is incomplete or malformed (e.g., "broken": [ }).
If you enable the custom-error-messages feature, CustomError is replaced by CustomErrorWithMessage, which provides a descriptive string explaining the failure (e.g., "invalid length 1, expected tuple struct Xy with 2 elements"). Note that these messages may be truncated to preserve memory efficiency in embedded environments.
// Example of handling a trailing characters error
let result = crate::from_str::<Xy>(r#"[10, 20, 30]"#);
assert_eq!(result, Err(crate::de::Error::TrailingCharacters));
// Example of a custom error with the 'custom-error-messages' feature
// #[cfg(feature = "custom-error-messages")]
// assert_eq!(result, Err(crate::de::Error::CustomErrorWithMessage("...".parse().unwrap())));