I’m working with an API that sometimes returns null
values for certain fields. I’m using Rust to fetch and process this data, but I want to ensure that structs containing optional string fields deserialize correctly.
Currently, I’m using #[serde(default)]
for the description field in my struct:
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
struct Info {
#[serde(default)]
description: String, // Use default value for missing description
}
However, my goal is to handle potential null values in the API response and make sure deserialization works as expected.
Are there any recommendations for further improvement or alternative approaches I should consider for handling optional string values during deserialization?
2
Answers
The way I typically handle this is to use
Option<String>
. Then, if the value isnull
, you get aNone
, and if the value is a string, you getSome(String)
. That works for JSON, CBOR, and most related serialization formats where you can have either a string or a null.If you want to then use a default value, you can do so, like so:
To supplement the other answer, it is possible to handle this case without typing
description
as anOption<String>
(should you not want it to be anOption
) and even specifying some other value to use instead of the empty string if the value is missing or null. You can do this using#[serde(default)]
and#[serde(deserialize_with)]
like this:(Playground)