Can json payloads be strongly typed? Or should all the fields be String? #2130
-
Lets say I have a route and I want to accept a Json payload like so; pub async fn check_sigs(Json(v): Json<SpecialType>) -> Result<Json<Value>, AppError> {}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpecialType {
pub context: Context,
pub siglist: Vec<Siglist>,
} Is this possible? I can't find an example that has something like it. The purpose of this is to avoid having to cast the type in my handler and move that code out elsewhere. Currently, I can only get it to work like this, where instead of my custom type, I have #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpecialType {
pub context: String,
pub siglist: Vec<Siglist>,
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Yea you can use custom types in JSON, that’s just using serde. JSON only supports strings as map keys but otherwise it should work. |
Beta Was this translation helpful? Give feedback.
-
Ok for posterity, my issue is that the underlying crate expands the the type in an unexpected way. The solution to this is to annotate the field in the struct with the problematic type with |
Beta Was this translation helpful? Give feedback.
Ok for posterity, my issue is that the underlying crate expands the the type in an unexpected way.
The solution to this is to annotate the field in the struct with the problematic type with
#[serde(deserialize_with = "my_deserialize_fn")]