Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize errors when using #[serde(flatten)] with HashMap<usize, T> #2628

Closed
r4ve1 opened this issue Oct 13, 2023 · 2 comments
Closed

Deserialize errors when using #[serde(flatten)] with HashMap<usize, T> #2628

r4ve1 opened this issue Oct 13, 2023 · 2 comments

Comments

@r4ve1
Copy link

r4ve1 commented Oct 13, 2023

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Deserialize, Serialize, Debug)]
struct A {
    #[serde(flatten)]
    b: B,
}

#[derive(Deserialize, Serialize, Debug)]
struct B {
    map: HashMap<usize, String>,
}

fn main() {
    let a = A {
        b: B {
            map: HashMap::from([(1, "a".to_string()), (2, "b".to_string())]),
        },
    };
    let s = serde_json::to_string(&a).unwrap();
    println!("{}", s);
    let aa: A = serde_json::from_str(&s).unwrap();
    // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: string \"1\", expected usize", line: 1, column: 25)', src\main.rs:23:42
    println!("{:?}", aa);
}

however when deleting the #[serde(flatten)] the deserialize won't error

@Mingun
Copy link
Contributor

Mingun commented Oct 13, 2023

This is duplicate of #1183. In JSON map keys can be only strings, so serde_json::Deserializer::deserialize_any returns strings to you. Flattening buffers the input using generic deserializer that uses serde_json::Deserializer::deserialize_any to capture data and then provide then. Unfortunately, because it is general, it is not aware that it's responsibility of the JSON key deserializer to convert strings to integers. From the other hand, usize::deserialize doesn't accept strings as valid input and returns error that you're see.

@r4ve1
Copy link
Author

r4ve1 commented Oct 14, 2023

I see, thanks

@r4ve1 r4ve1 closed this as completed Oct 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants