How do I serialize or deserialize an Arc in Serde?

Serde provides implementations of Serialize and Deserialize for Arc<T> and Rc<T>, but only if the rc feature is enabled. There’s a comment on Serde’s reference website explaining why: Opt into impls for Rc<T> and Arc<T>. Serializing and deserializing these types does not preserve identity and may result in multiple copies of the same data. Be … Read more

How do I use Serde to serialize a HashMap with structs as keys to JSON?

You can use serde_as from the serde_with crate to encode the HashMap as a sequence of key-value pairs: use serde_with::serde_as; // 1.5.1 #[serde_as] #[derive(Serialize, Deserialize, Debug)] struct Bar { #[serde_as(as = “Vec<(_, _)>”)] x: HashMap<Foo, f64>, } Which will serialize to (and deserialize from) this: { “x”:[ [{“x”: 0}, 0.0], [{“x”: 1}, 0.0], [{“x”: 2}, … Read more

How can I deserialize JSON with a top-level array using Serde?

You can simply use a Vec: use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Foo { data: String, } fn main() -> Result<(), serde_json::Error> { let data = r#”[ { “data”: “value1” }, { “data”: “value2” }, { “data”: “value3” } ]”#; let datas: Vec<Foo> = serde_json::from_str(data)?; for data in datas.iter() { println!(“{:#?}”, data); } Ok(()) … Read more

Generate pretty (indented) JSON with serde

The serde_json::to_string_pretty function generates pretty-printed indented JSON. use serde_json::json; fn main() { let obj = json!({“foo”:1,”bar”:2}); println!(“{}”, serde_json::to_string_pretty(&obj).unwrap()); } This approach defaults to 2 spaces of indentation, which happens to be what you asked for in your question. You can customize the indentation by using PrettyFormatter::with_indent. use serde::Serialize; use serde_json::json; fn main() { let obj … Read more

How can I deserialize an optional field with custom functions using Serde?

The default behaviour of struct deserialization is to assign fields with their respective default value when they are not present in their serialized form. Note that this is different from the container #[serde(default)] attribute, which fills in the fields with the struct’s default value. #[derive(Debug, PartialEq, Deserialize)] pub struct Foo<‘a> { x: Option<&’a str>, } … Read more

How to transform fields during deserialization using Serde?

The deserialize_with attribute The easiest solution is to use the Serde field attribute deserialize_with to set a custom serialization function for your field. You then can get the raw string and convert it as appropriate: use serde::{de::Error, Deserialize, Deserializer}; // 1.0.94 use serde_json; // 1.0.40 #[derive(Debug, Deserialize)] struct EtheriumTransaction { #[serde(deserialize_with = “from_hex”)] account: u64, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)