Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// use like `#[serde(with = "string")]` after bringing into scope
- pub mod string {
- use std::fmt::Display;
- use std::io::Write as _;
- use std::str::FromStr;
- use std::marker::PhantomData;
- use serde::{de::Visitor, Deserializer, Serializer};
- pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
- where
- T: Display,
- S: Serializer,
- {
- let mut buf: smallvec::SmallVec<[u8; 64]> = smallvec::SmallVec::new();
- write!(buf, "{}", value).unwrap();
- let s = std::str::from_utf8(&buf).unwrap();
- serializer.serialize_str(s)
- }
- struct ParsingVisitor<T>(std::marker::PhantomData<fn() -> T>);
- impl<'de, T> Visitor<'de> for ParsingVisitor<T>
- where
- T: FromStr,
- T::Err: Display,
- {
- type Value = T;
- fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
- formatter.write_str("a string")
- }
- fn visit_str<E>(self, value: &str) -> Result<T, E>
- where
- E: serde::de::Error,
- {
- value.parse().map_err(E::custom)
- }
- }
- pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
- where
- T: FromStr,
- T::Err: Display,
- D: Deserializer<'de>,
- {
- deserializer.deserialize_str(ParsingVisitor(PhantomData))
- }
- }
- use serde_derive::{Serialize, Deserialize};
- #[derive(Debug, Serialize, Deserialize)]
- struct Foobar {
- #[serde(with = "string")]
- something: i32,
- }
- fn main() {
- let s = serde_json::to_string(&Foobar { something: 3 }).unwrap();
- println!("json: {}", s);
- println!("unjson: {:?}", serde_json::from_str::<Foobar>(&s).unwrap());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement