serde

How can I use Serde with a JSON array with different objects for successes and errors?

大城市里の小女人 提交于 2019-11-26 09:56:05
问题 I want to use Serde to create an array with error messages as well as proper objects: extern crate serde; // 1.0.70 #[macro_use] extern crate serde_derive; // 1.0.70 extern crate serde_json; // 1.0.24 #[derive(Serialize, Deserialize, Debug)] pub struct MyError { error: String, } #[derive(Serialize, Deserialize, Debug)] pub struct MyAge { age: i32, name: String, } fn get_results(ages: Vec<i32>) -> Vec<MyAge> { let mut results = vec![]; for age in ages { if age < 100 && age > 0 { results.push

How to transform fields during serialization using Serde?

不想你离开。 提交于 2019-11-26 07:48:54
问题 How can I apply a transformation to a field before serialization? For example, how can I ensure that the fields lat and lon in this struct definition are rounded to at most 6 decimal places before being serialized? #[derive(Debug, Serialize)] struct NodeLocation { #[serde(rename = \"nodeId\")] id: u32, lat: f32, lon: f32, } 回答1: The serialize_with attribute You can use the serialize_with attribute to provide a custom serialization function for your field: #[macro_use] extern crate serde

Lifetime error when creating a function that returns a value implementing serde::Deserialize

一笑奈何 提交于 2019-11-26 06:49:23
问题 I\'m using serde and serde_json 1.0 to decode data from a base64 string: fn from_base64_str<T: Deserialize>(string: &str) -> T { let slice = decode_config(string, URL_SAFE).unwrap(); serde_json::from_slice(&slice).unwrap() } When I compile, I got this: error[E0106]: missing lifetime specifier --> src/main.rs:6:23 | 6 | fn from_base64_str<T: Deserialize>(string: &str) -> T { | ^^^^^^^^^^^ expected lifetime parameter Checking the serde doc, Deserialize is defined as: pub trait Deserialize<\'de>