Deserialize and flatten single item array

Hello.

Is there a way to deserialize a vector into a struct? I looked at annotating with "flatten" but this could only be used for a hashmap.

The field "invitees" is a json array and turned into a vector. There is always one item in the list.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Invitee {
    #[serde(rename = "displayName")]
    display_name: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Event {
    invitees: Vec<Invitee>,
}

When I access the item I have to get the first and only one and then unwrap it. I was wondering if there was a way to annotate this to always return the only or just the first item. If there are any others then happy for them to be ignored.

event.invitees.first().unwrap().display_name

I have looked at a deserialization function but wondered if there was a more succinct way with any annotations or anything simpler.

Any help is much appreciated.

If there will always be exactly one element in the input, you can use a 1-element tuple or array. A tuple is convenient here because you can use dot syntax to get its one field:

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Invitee {
    #[serde(rename = "displayName")]
    display_name: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Event {
    invitees: (Invitee,),
}

fn main() {
    let x: Event = serde_json::from_str(r#"{"invitees":[{"displayName":"Alice"}]}"#).unwrap();
    dbg!(&x);
    dbg!(&x.invitees.0.display_name);
}

I can’t think of a way to ask serde to ignore further elements other than by customizing the deserialization with impl Deserialize for... or #[serde(from)]. But, you can write event.invitees[0] in place of .first().unwrap(). Note that either of these will panic if the input has zero elements.

Thank you @kpreid that seems simpler for what I was looking to achieve. I'll use this approach.