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
XiangruLiu0 opened this issue Oct 13, 2023 · 2 comments
Closed

Comments

@XiangruLiu0
Copy link

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.

@XiangruLiu0
Copy link
Author

I see, thanks

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