Given the following struct definition.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub (in crate) struct ResponseError {
pub status: StatusCode,
pub title: String,
pub message: String,
pub trace: Option<String>,
}
How to group some of the fields into a namespace (nest them) during serialization? For example, grouping the title, message, and trace fields into error namespace like the following.
{
"status": 0,
"error": {
"title": "",
"message": "",
"trace": "",
},
}
The goal is to be able to create a flat struct in Rust while outputting structured response. This is the approach I can came up with.
impl Serialize for ResponseError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Color", if self.trace.is_some() { 4 } else { 3 })?;
state.serialize_field("status", &self.status)?;
state.serialize_field("error.title", &self.title)?;
state.serialize_field("error.message", &self.message)?;
if let Some(trace) = self.trace {
state.serialize_field("error.trace", &self.trace)?;
};
state.end()
}
}