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 do I serialize an enum without including the name of the enum variant?

You can use the untagged attribute which will produce the desired output. You won’t need to implement Serialize yourself with this: #[derive(Debug, Serialize)] #[serde(untagged)] enum TValue<‘a> { String(&’a str), Int(&’a i32), } If you wanted to implement Serialize yourself, I believe you want to skip your variant so you should not use serialize_newtype_variant() as it … Read more

How to implement `serde::Serialize` for a boxed trait object?

For serializing Serde trait objects you should use erased-serde. #[macro_use] extern crate serde_derive; #[macro_use] extern crate erased_serde; extern crate serde; extern crate serde_json; #[derive(Serialize)] struct Card { sections: Vec<Section>, } #[derive(Serialize)] struct Section { header: String, widgets: Vec<Box<dyn WidgetTrait>>, } #[derive(Serialize)] struct Image { image_url: String, } #[derive(Serialize)] struct KeyValue { top_label: String, content: String, … Read more

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

Building off of E_net4’s answer, you can also create an enum for the three possibilities: #[derive(Debug)] enum Patch<T> { Missing, Null, Value(T), } impl<T> Default for Patch<T> { fn default() -> Self { Patch::Missing } } impl<T> From<Option<T>> for Patch<T> { fn from(opt: Option<T>) -> Patch<T> { match opt { Some(v) => Patch::Value(v), None => … Read more

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

Here’s one way of doing that: #[macro_use] extern crate serde_derive; // 1.0.117 extern crate serde; // 1.0.117 extern crate serde_json; // 1.0.59 #[derive(Serialize, Deserialize, Debug)] pub struct MyError { error: String, } #[derive(Serialize, Deserialize, Debug)] pub struct MyAge { age: i32, name: String, } #[derive(Debug)] enum AgeOrError { Age(MyAge), Error(MyError), } impl serde::Serialize for AgeOrError … Read more