I am trying to use the custom implementation in Serialize
trait of Serde
. Here is the code (playground):
use serde::ser::{Serialize, Serializer, SerializeStruct};
struct Data {
key: String, // or &str
value: i32,
}
impl Serialize for Data {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Data", 1)?;
// let key = (&self.key).to_string();
// state.serialize_field(&*key, &self.value)?; //shows lifetime error
state.serialize_field("key", &self.value)?;
state.end()
}
}
fn main() {
let data = Data {
key: String::from("age"),
value: 21,
};
let json = serde_json::to_string_pretty(&data).unwrap();
println!("the JSON is: {}", json)
}
by default, serde
serialize Data
as:
{
"key": "age",
"value": 21
}
but, i want this:
{
"age": 21,
}
This question is also similar, but I need more info in this context.
CodePudding user response:
Your Data
struct is essentially a singleton map. You should serialize it as such:
impl Serialize for Data {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry(&self.key, &self.value)?;
map.end()
}
}