path-to-error icon indicating copy to clipboard operation
path-to-error copied to clipboard

Field name and line numbers are missing in internally tagged enum

Open dkoontz opened this issue 6 years ago • 6 comments

Here is a test case that shows the failure. Comment/uncomment one of the let json_deserializer = lines to toggle between the JSON test data. The output for the failing case is:

Error parsing field: ., at position 0:0
invalid type: string "500", expected u32
#![feature(proc_macro_hygiene, decl_macro)]

use serde_derive::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(tag = "type", content = "content")]
pub enum TestStruct {
    A(u32),
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub enum Wrapper {
    B { value: TestStruct },
}

#[allow(dead_code)]
const WORKING_JSON: &'static str = r#"
{
	"type": "B",
	"value": { "type": "A", "content": 500 }
}"#;

#[allow(dead_code)]
const FAILING_FIELD_NAME_AND_LINE: &'static str = r#"
{
	"type": "B",
	"value": { "type": "A", "content": "500" }
}"#;

fn main() {
    // Example of JSON deserialization error, speficially a string is provided instead of u32.
    // Comment out one of these two lines to see the difference between the working and failing JSON
    let json_deserializer = &mut serde_json::Deserializer::from_str(WORKING_JSON);
    // let json_deserializer = &mut serde_json::Deserializer::from_str(FAILING_FIELD_NAME_AND_LINE);

    let result: Result<Wrapper, _> = serde_path_to_error::deserialize(json_deserializer);
    match result {
        Ok(e) => println!("{:?}", e),
        Err(e) => {
            let path = e.path().to_string();
            let i = e.into_inner();
            println!(
                "Error parsing field: {}, at position {}:{}\n{}",
                path,
                i.line(),
                i.column(),
                i
            )
        }
    }
}

dkoontz avatar Feb 13 '19 17:02 dkoontz

Is there any solution to this? For TOML deserializing, it seems to detect the position always at the end of the file.

novacrazy avatar Nov 04 '19 10:11 novacrazy

Is this an implementation issue or some design issue in serde or something?

mohe2015 avatar Feb 06 '24 23:02 mohe2015