1

I have difficulty understanding how to deal with polymorphic objects. I have JSON input which I want to deserialize as a struct which can hold another struct of type A or B. Each one implements the G trait:

pub trait Action {}

impl Action for SendMessage {}

#[derive(Debug, Deserialize, Serialize)]
struct SendMessage {
    msg: String,
}

impl Action for SendEmail {}

struct SendEmail {
    recipient: String,
    msg: String,
}

#[derive(Debug, Deserialize, Serialize)]
struct ApiResponse<T: Action> {
    status: String,
    data: T,
}

fn main() {
    let payload = r#"
    {
        "status": "200",
        "data": {
                "msg": "toto"
        }
    }
    "#;

    let test: ApiResponse = serde_json::from_str(payload).unwrap(); // Return Error
    let test: ApiResponse<SendEmail> = serde_json::from_str(payload).unwrap(); // Is ok
    let test: ApiResponse<SendMessage> = serde_json::from_str(payload).unwrap(); // Return Error
}

What is the idiomatic way to store the result in my test variable if I don't know the content of my payload?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • It looks like your question might be answered by the answers of [How do I deserialize into trait, not a concrete type?](https://stackoverflow.com/q/42392935/155423); [How can I use Serde with a JSON array with different objects for successes and errors?](https://stackoverflow.com/a/42034863/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jan 20 '20 at 03:26
  • Does this answer your question? [How can I use Serde with a JSON array with different objects for successes and errors?](https://stackoverflow.com/questions/37561593/how-can-i-use-serde-with-a-json-array-with-different-objects-for-successes-and-e) – Axel Schafers Jan 20 '20 at 17:02

0 Answers0