serde

How to transform fields during serialization using Serde?

[亡魂溺海] 提交于 2019-11-28 01:51:23
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, } krdln 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_derive; extern crate serde; use serde::Serializer; fn round_serialize<S>(x: &f32, s: S) -> Result<S::Ok, S:

How can deserialization of polymorphic trait objects be added in Rust if at all?

☆樱花仙子☆ 提交于 2019-11-27 23:34:49
I'm trying to solve the problem of serializing and deserializing Box<SomeTrait> . I know that in the case of a closed type hierarchy, the recommended way is to use an enum and there are no issues with their serialization, but in my case using enums is an inappropriate solution. At first I tried to use Serde as it is the de-facto Rust serialization mechanism. Serde is capable of serializing Box<X> but not in the case when X is a trait. The Serialize trait can’t be implemented for trait objects because it has generic methods. This particular issue can be solved by using erased-serde so

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

梦想与她 提交于 2019-11-27 17:30:45
问题 I want to serialize and deserialize a chrono::NaiveDate with custom functions, but the Serde book does not cover this functionality and the code docs also do not help. #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate chrono; use chrono::NaiveDate; mod date_serde { use chrono::NaiveDate; use serde::{self, Deserialize, Serializer, Deserializer}; pub fn serialize<S>(date: &Option<NaiveDate>, s: S) -> Result<S::Ok, S::Error> where S: Serializer {

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

无人久伴 提交于 2019-11-27 09:07:40
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(MyAge { age: age, name: String::from("The dude"), }); } else { results.push(MyError { error: String:

How can I distinguish between a deserialized field that is missing and one that is null?

◇◆丶佛笑我妖孽 提交于 2019-11-27 06:02:50
问题 I'd like to use Serde to parse some JSON as part of a HTTP PATCH request. Since PATCH requests don't pass the entire object, only the relevant data to update, I need the ability to tell between a value that was not passed, a value that was explicitly set to null , and a value that is present. I have a value object with multiple nullable fields: struct Resource { a: Option<i32>, b: Option<i32>, c: Option<i32>, } If the client submits JSON like this: {"a": 42, "b": null} I'd like to change a to

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

折月煮酒 提交于 2019-11-27 05:29:24
I have a some JSON data that is returned from a web service. The JSON is a top-level array: [ { "data": "value1" }, { "data": "value2" }, { "data": "value3" } ] Using serde_derive to make struct s I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array. Am I missing something, or can Serde not deserialize top level-arrays? Stargateur You can use a Vec : extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; use serde_json::Error; #[derive(Serialize, Deserialize, Debug)] struct Foo { data:

Why can Serde not derive Deserialize for a struct containing only a &Path?

社会主义新天地 提交于 2019-11-26 22:08:44
问题 I tried to derive serde::Deserialize for a struct containing a reference to a Path . This yielded an error message which doesn't occur if you replace &'a Path with &'a str . What causes the different behaviours of #[derive(Deserialize)] ? Playground #!/bin/cargo script //! ```cargo //! [dependencies] //! serde_derive="1.0" //! serde="1.0" //! ``` extern crate serde_derive; use serde_derive::*; #[derive(Deserialize)] struct A<'a> { a: &'a std::path::Path, //a: &'a str, } fn main() {} error

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

流过昼夜 提交于 2019-11-26 19:11:25
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>: Sized { So I added the lifetime: fn from_base64_str<'de, T: Deserialize<'de>>(string: &str) -> T { let

How to transform fields during deserialization using Serde?

家住魔仙堡 提交于 2019-11-26 13:52:09
I'm using Serde to deserialize an XML file which has the hex value 0x400 as a string and I need to convert it to the value 1024 as a u32 . Do I need to implement the Visitor trait so that I separate 0x and then decode 400 from base 16 to base 10? If so, how do I do that so that deserialization for base 10 integers remains intact? 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,

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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 09:59:31
问题 I have a some JSON data that is returned from a web service. The JSON is a top-level array: [ { \"data\": \"value1\" }, { \"data\": \"value2\" }, { \"data\": \"value3\" } ] Using serde_derive to make struct s I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array. Am I missing something, or can Serde not deserialize top level-arrays? 回答1: You can use a Vec : extern crate serde; extern crate serde_json; #[macro_use]