Deserialize a map with one field and extract only the field's value

I'm writing a (non-general-purpose) GraphQL client, so I often end up having to deserialize JSON maps like {"repository": DATA} that contain only one field where I want to end up with only that field's value. So far, I've just been doing this by defining a bunch of types like:

#[derive(Deserialize)]
struct Response {
    repository: InterestingData,
}

and then just returning the repository field of the deserialized Response, but this is repetitive. I tried to at least get rid of all the singleton struct definitions by instead deserializing to (InterestingData,) and returning the .0 field (thinking that, if a JSON list can be deserialized to a struct, surely deserializing the other way would work), but serde-json didn't like that. serde_with didn't seem to have anything helpful for this either.

At the moment, it looks like my best option is to define a struct Singleton<T>(pub T) type and give it a custom Deserialize impl that expects a one-field map & extracts the field's value, but I'm wondering if there's another way I've overlooked.

Someone else just asked the same question Deserialize and serialize struct to map with a single field

Despite the similar titles, that question appears to be quite different. Among other things, it looks like that asker wants to be able to retrieve the field name.

Try this: Rust Playground

That's the sort of thing I was referring to with my Singleton<T> idea in my original post. My question is not how to implement that type specifically; it is whether there are any other approaches (using either serde's built-in features or a third-party library) that would solve my problem without me having to define a custom type or custom Deserialize impl.

No, I don't think so. Unless you want to implement you own Deserialize proc-macro.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.