Home > Blockchain >  Working with optional JSON fields in Rust, avoid None / null in JSON, use undefined instead
Working with optional JSON fields in Rust, avoid None / null in JSON, use undefined instead

Time:04-12

is there a better (leaner) way to express my self other than this:

#[derive(Serialize, Deserialize, Debug, Default]
pub struct PagingObject {
  #[serde(skip_serializing_if = "Option::is_none")]
  offsetId: Option<String>,     // offset expressed as element id (uuid)
  #[serde(skip_serializing_if = "Option::is_none")]
  offset: Option<i32>,          // offset expressed as index (numeric)
  #[serde(skip_serializing_if = "Option::is_none")]
  total: Option<i32>,           // total number of elements
  #[serde(skip_serializing_if = "Option::is_none")]
  totalPages: Option<i32>,      // total number of pages based on limit
  #[serde(skip_serializing_if = "Option::is_none")]
  previous: Option<String>,     // link to previous page
  #[serde(skip_serializing_if = "Option::is_none")]
  next: Option<String>,         // link to next page
  #[serde(skip_serializing_if = "Option::is_none")]
  limit: Option<i32>            // the limit used
}

CodePudding user response:

serde does not have any built-in way on dealing with this. However, the third-party serde_with::skip_serializing_none macro addresses this problem. The usage is as simple as adding another attribute before the derive.

#[serde_with::skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Default]
pub struct PagingObject {
  offsetId: Option<String>,     // offset expressed as element id (uuid)
  offset: Option<i32>,          // offset expressed as index (numeric)
  total: Option<i32>,           // total number of elements
  totalPages: Option<i32>,      // total number of pages based on limit
  previous: Option<String>,     // link to previous page
  next: Option<String>,         // link to next page
  limit: Option<i32>            // the limit used
}
  • Related