0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alex Smith
  • 311
  • 1
  • 3
  • 14
  • It looks like your question might be answered by the answers of [How to transform fields during deserialization using Serde?](https://stackoverflow.com/a/46755370/155423); [Convert two types into a single type with Serde](https://stackoverflow.com/q/37870428/155423); [How can I use Serde with a JSON array with different objects for successes and errors?](https://stackoverflow.com/q/37561593/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 17 '20 at 16:47
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), types, traits, fields, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Jun 17 '20 at 16:47
  • 2
    And, for my own sanity, it's "amount". – Shepmaster Jun 17 '20 at 16:47
  • I've kinda got it: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3a6a2df0c4062ebc30efac1a659f015a And tried to implement it for more complex struct. But do not understand how to handle deserialization error properly – Alex Smith Jun 17 '20 at 18:18

0 Answers0