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

How to transform fields during serialization using Serde?

The serialize_with attribute You can use the serialize_with attribute to provide a custom serialization function for your field: use serde::{Serialize, Serializer}; // 1.0.104 fn round_serialize<S>(x: &f32, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { s.serialize_f32(x.round()) } #[derive(Debug, Serialize)] pub struct NodeLocation { #[serde(rename = “nodeId”)] id: u32, #[serde(serialize_with = “round_serialize”)] lat: f32, #[serde(serialize_with = … 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