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

Serialization always fails with "key must be a string" #887

Closed
br-olf opened this issue May 3, 2022 · 1 comment
Closed

Serialization always fails with "key must be a string" #887

br-olf opened this issue May 3, 2022 · 1 comment

Comments

@br-olf
Copy link

br-olf commented May 3, 2022

Hi, I don't know if this issue belongs here or to serde itself.

I try to serialize this object

use serde;
use serde_json;
use std::collections::BTreeMap;
use std::path::PathBuf;

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DedupTree {
    hash_tree: BTreeMap<[u8; 32], Vec<PathBuf>>,
    file_tree: BTreeMap<PathBuf, [u8; 32]>,
}

impl DedupTree {
    pub fn to_json(&self) -> String {
        serde_json::to_string(&self).unwrap()
    }

    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

but any time I want to use to_json() I get this error:
Error("key must be a string", line: 0, column: 0)

I tried a number of different approaches to fix this by implementing serialize for [u8,32] myself but eventually I always got the same error.
As far as I see from the docs all used types (BTreeMap,[u8; 32],Vec, PathBuf) are supported by serde.

@dtolnay
Copy link
Member

dtolnay commented May 3, 2022

I think this is behaving correctly. JSON maps only have string keys. Map keys are not allowed to be arrays in JSON.

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