This is likely related to #540, but it seems a somewhat separate case.
This took me a long time to figure out; a better error message could have definitely shortened that time.
Expected behavior (1)
Attempting to deserialize a non-empty array into an object should fail with a meaningful error.
For example, this is the error returned when attempting to deserialize a string into an object:
Error("invalid type: string \"XX\", expected struct Item", line: 3, column: 20)
Actual behavior (1)
This is the actual error being returned, which seems to indicate invalid JSON syntax instead:
: Error("trailing characters", line: 3, column: 18)
Expected behavior (2)
Attempting to deserialize an empty array into an object should fail with a meaningful error.
Actual behavior (2)
It actually just produces an empty object.
Example code to reproduce
use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Value;
fn main() {
let data = r#"
{"items": {
"example": [1]
}}
"#;
let v: Value = serde_json::from_str(data).expect("");
println!("{:#?}", &v);
let v: MyObj = serde_json::from_str(data).expect("");
println!("{:#?}", &v);
}
#[derive(Deserialize, Debug)]
pub struct MyObj {
items: Option<HashMap<String, Item>>,
}
#[derive(Deserialize, Debug)]
struct Item {}
Which fails with this output:
Object {
"items": Object {
"example": Array [
Number(1),
],
},
}
thread 'main' (845267) panicked at src/main.rs:16:47:
: Error("trailing characters", line: 3, column: 18)
Even more confusingly, it seems to work perfectly fine if the array is empty, for example:
{"items": { "example": [] }}
Cargo.toml for reference:
[package]
name = "example"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
This is likely related to #540, but it seems a somewhat separate case.
This took me a long time to figure out; a better error message could have definitely shortened that time.
Expected behavior (1)
Attempting to deserialize a non-empty array into an object should fail with a meaningful error.
For example, this is the error returned when attempting to deserialize a string into an object:
Actual behavior (1)
This is the actual error being returned, which seems to indicate invalid JSON syntax instead:
Expected behavior (2)
Attempting to deserialize an empty array into an object should fail with a meaningful error.
Actual behavior (2)
It actually just produces an empty object.
Example code to reproduce
Which fails with this output:
Even more confusingly, it seems to work perfectly fine if the array is empty, for example:
{"items": { "example": [] }}Cargo.tomlfor reference: