The first post had a couple errors that made things confusing. I have an accurately formatted JSON response, but I still can’t seem to deserialize it.

I keep getting an error where the response isn’t matching up as expected: Error(“data did not match any variant of untagged enum NationResponse”

I have a JSON response that looks like this:

 {
      {
            "id": 1,
            "country": "usa"
        },
        [
            {
                "id": 1,
                "age": 37,
                "name": "John"
            },
            {
                "id": 2,
                "age": 21,
                "name": "Nick"
            },
        ]
}

And I’m trying to deserialize it, but I can’t seem to get it right. Isn’t this accurate?

#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum NationResponse {
    Nation(Nation),
    People(Vec),
}

struct Person {
    id : i32,
    age : i32,
    name : String
}

struct Nation {
    id : i32,
    country : String
}

Edit:

The problem I was actually experiencing was trying to use an enum as the response. Yes the formatting for my example was wrong (it should have been an array). But the structure besides that was accurate.

What I needed was Vec>

  • Envis10n
    link
    fedilink
    129 months ago

    So, no. With the way you have it setup right now you would need to adjust your JSON structure to have the nation info be under a key, as well as the people array.

    {
        "Nation": {...},
        "People": [...],
    }
    

    Every value has to have a key, unless it is the only value being serialized.

    [1,2]
    

    Is valid JSON, but

    { {"Id":1} }
    

    Is not

    • TehPers
      link
      fedilink
      English
      1
      edit-2
      9 months ago

      An untagged enum doesn’t need keys for the variants. It just tries to deserialize into each variant in the order defined.

      That being said, you’re right that the JSON is invalid.

      • Envis10n
        link
        fedilink
        19 months ago

        Yeah, I wasn’t trying to imply that it was a problem on the rust side or that they needed to name the keys that way, just that the JSON does need to have keys because that is how JSON works