I have the following struct
#[derive(Serialize)]
pub struct MyStruct {
pub id: String,
pub score: f32,
pub json: String,
}
The json
field always contains a valid JSON object already stringified.
Given an instance, I would like to serialize it with the JSON content.
Something like:
let a = MyStruct {
id: "my-id".to_owned(),
score: 20.3,
json: r#"{
"ffo": 4
}"#,
};
let r = to_string(&a).unwrap();
assert_eq!(r, r#"{
"id": "my-id",
"score": 20.3,
"json": {
"ffo": 4
}
}"#);
NB: I don’t need to support different serialization formats, only JSON.
NB2: I’m sure that json
field always contains a valid JSON object.
NB3: commonly I use serde but I’m open to using different libraries.
How can I do that?
Edit:
I would like to avoid deserializing the string during the serialization if possible.
2
Answers
You can do it, but you have to override the default serialization behaviour somehow. You can do this either by wrapping your
json
field in a newtype (likestruct JsonString(String)
and implementingSerialize
manually for that type, or you can use the#[serde(serialize_with = "...")]
field attribute to ad-hoc change the serialization of thejson
field. Here’s an example of using theserialize_with
field attribute:Playground.
serde_json
has araw_value
feature for something like this:Cargo.toml
lib.rs
But the simplest (and most error-prone and least extensible) solution is simple string manipulation: