I have a case when I need to perform some type conversions on incoming JSON. Different clients send pretty much the same data in different types:
{"amount": 49.90}
{"amount": "49.90"}
My struct & handler:
struct Amount {
pub amount: f64,
}
pub async fn amount(
amount: ValidatedJson<Amount>
) -> Result<HttpResponse, AppError> {
let amount: Amount = amount.to_inner();
...
}
When I'm trying to perform JSON to struct serialization, a deserialization error occurs.
I've tried to serialize raw body using serde_json, but did not figure out how to make existence checks and error handling properly, so I stuck with:
let body: String = String::from_utf8(bytes.to_vec()).map_err(|e| {
// logs
})?;
let body: Value = serde_json::from_str(body.as_str()).map_err(|e| {
// logs
})?;
let body = body.as_object().unwrap();
let amount: f32 = body.get("amount")?.as_f64()?;
This can be done only in nightly using try_trait
. And this is kinda a dumb way I think.
What are my options? I'm using Rust 1.43 and actix-web 2.0.0.