nop_json/validate_json.rs
1pub use nop_json_derive::*;
2
3/// During deserialization process, you may want to complain on invalid fields combination in struct.
4/// Every type that implements [TryFromJson](trait.TryFromJson.html) must also implement `ValidateJson`.
5/// This trait introduces function `validate_json()`. `try_from_json()` calls this function right after
6/// it converted JSON string to target type, and deserialization will stop if `validate_json()` returns `Err`.
7///
8/// `ValidateJson` can be implemented automatically through `#[derive(TryFromJson, ValidateJson)]`.
9/// Default implementation always accepts the validation. To validate the type you need to implement this trait manually.
10///
11/// # Examples
12///
13/// ```
14/// use nop_json::{Reader, TryFromJson};
15/// use std::io;
16///
17/// #[derive(TryFromJson, Debug)]
18/// struct FromTo {from: i32, to: i32}
19///
20/// impl nop_json::ValidateJson for FromTo
21/// { fn validate_json(self) -> Result<Self, String>
22/// { if self.from <= self.to
23/// { Ok(self)
24/// }
25/// else
26/// { Err("to must be after from".to_string())
27/// }
28/// }
29/// }
30///
31/// let mut reader = Reader::new(r#" {"from": 0, "to": 10} {"from": 3, "to": -1} "#.bytes());
32/// let obj_0: io::Result<FromTo> = reader.read();
33/// let obj_1: io::Result<FromTo> = reader.read();
34/// assert!(obj_0.is_ok());
35/// assert!(obj_1.is_err());
36/// ```
37pub trait ValidateJson: Sized
38{ fn validate_json(self) -> Result<Self, String>
39 { Ok(self)
40 }
41}