0

i call an api that returns a json like this one

[
    {
        "id":"b8b2f91952f1fb757663073fa8f6be73",
        "name":"test1",
        "colors":[
            {
                "name":"Red",
                "number":"0"
            },
            {
                "name":"Blue",
                "number":"1"
            }
        ]
    },
    {
        "id":"91ff6b1fb7b8b2f57663073952fa8e73",
        "name":"test2",
        "colors": null
    }
]

i made this struct

#[derive(Serialize, Deserialize, Debug)]
struct FinalScores {
    id: String,
    name: String,
    colors: Vec<Colors>
}

#[derive(Serialize, Deserialize, Debug)]
struct Colors{
    name: String,
    number: String
}

i map the json into the struct with this

let score_request_url = "https://api.test.com";

let score_response = reqwest::get(score_request_url).await?;

let score_infos: Vec<FinalScores> = score_response.json().await?;

but i get an error because he is expecting always a vec of Colors in the colors camp but sometimes is not a vec but is just null

invalid type: null, expected a string

anyone who know how to solve this?

GranBoh
  • 67
  • 8
  • Does this answer your question? [How do I change Serde's default implementation to return an empty object instead of null?](https://stackoverflow.com/questions/46993079/how-do-i-change-serdes-default-implementation-to-return-an-empty-object-instead) – cafce25 Nov 25 '22 at 09:35

1 Answers1

0

I'd recommend you to use serde_with's DefaultOnNull:

#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug)]
struct FinalScores {
    id: String,
    name: String,
    #[serde_as(deserialize_as = "serde_with::DefaultOnNull")]
    colors: Vec<Colors>
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77