为什么在尝试使用serde_json解析数据时总是出现“尾随字符”错误?

时间:2019-06-29 11:00:23

标签: json rust

我有一台服务器以JSON格式返回请求。尝试解析数据时,总是出现“尾随字符”错误。仅当从邮递员

获取JSON时才会发生这种情况
let type_of_request = parsed_request[1];
let content_of_msg: Vec<&str> = msg_from_client.split("\r\n\r\n").collect();

println!("{}", content_of_msg[1]); 
// Will print "{"username":"user","password":"password","email":"dwadwad"}"

let res: serde_json::Value = serde_json::from_str(content_of_msg[1]).unwrap();

println!("The username is: {}", res["username"]);

从邮递员那里获取数据时,会发生这种情况:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("trailing characters", line: 1, column: 60)', src\libcore\result.rs:997:5

但是在Rust中包含字符串时:

let j = "{\"username\":\"user\",\"password\":\"password\",\"email\":\"dwadwad\"}";

let res: serde_json::Value = serde_json::from_str(j).unwrap();

println!("The username is: {}", res["username"]);

它就像一种魅力:

The username is: "user"

编辑:显然,当我将消息读入缓冲区并将其转换为字符串时,它会保存缓冲区具有的所有NULL字符,这些字符当然是结尾字符。

1 个答案:

答案 0 :(得分:1)

查看serde json code,在相关的ErrorCode枚举元素上方找到以下注释:

/// JSON has non-whitespace trailing characters after the value.
TrailingCharacters,

因此,如错误代码所暗示的那样,您拥有一些不是空格的结尾字符。在您的代码段中,您说:

println!("{}", content_of_msg[1]); 
// Will print "{"username":"user","password":"password","email":"dwadwad"}"

如果您确实在此处复制并粘贴了打印的输出,我会注意到,我不希望输出用引号和尾引号引起来。您是自己包括这些内容还是它们是印刷内容的一部分?如果将它们打印出来,我怀疑那是您问题的根源。

编辑:

实际上,我几乎可以使用在Rust中使用带引号/尾部引号的原始字符串来重新创建它:

extern crate serde_json;

#[cfg(test)]
mod tests {
    #[test]
    fn test_serde() {
        let s =
            r#""{"username":"user","password":"password","email":"dwadwad"}""#;
        println!("{}", s);
        let _res: serde_json::Value = serde_json::from_str(s).unwrap();
    }
}

通过cargo test运行它会产生:

test tests::test_serde ... FAILED

failures:

---- tests::test_serde stdout ----
"{"username":"user","password":"password","email":"dwadwad"}"
thread 'tests::test_serde' panicked at 'called `Result::unwrap()` on an `Err` value: Error("trailing characters", line: 1, column: 4)', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.


failures:
    tests::test_serde

请注意,我的打印输出中还包含前导/尾引号,尽管在另一列,我也遇到TrailingCharacter错误。

编辑2:

根据您的评论,您自己添加了包装引号,您有一个已知的好字符串(在Rust中定义的字符串),并且您认为应该匹配但不匹配的字符串(一位来自邮递员)。

这是一个数据问题,因此我们应该检查数据。您可以修改以下代码,以对照其他字符串检查正确的字符串:

#[test]
fn test_str_comp() {
    // known good string we'll compare against                                                                                                                                             
    let good =
        r#"{"username":"user","password":"password","email":"dwadwad"}"#;
    // lengthened string, additional characters                                                                                                                                            
    // also n and a in username are transposed                                                                                                                                             
    let bad =
        r#"{"useranme":"user","password":"password","email":"dwadwad"}abc"#;
    let good_size = good.chars().count();
    let bad_size = bad.chars().count();
    for (idx, (c1, c2)) in (0..)
        .zip(good.chars().zip(bad.chars()))
        .filter(|(_, (c1, c2))| c1 != c2)
    {
        println!(
            "Strings differ at index {}: (good: `{}`, bad: `{}`)",
            idx, c1, c2
        );
    }
    if good_size < bad_size {
        let trailing = bad.chars().skip(good_size);
        println!(
            "bad string contains extra characters: `{}`",
            trailing.collect::<String>()
        );
    } else if good_size > bad_size {
        let trailing = good.chars().skip(bad_size);
        println!(
            "good string contains extra characters: `{}`",
            trailing.collect::<String>()
        );
    }

    assert!(false);
}

对于我的示例,这将导致失败:

test tests::test_str_comp ... FAILED

failures:

---- tests::test_str_comp stdout ----
Strings differ at index 6: (good: `n`, bad: `a`)
Strings differ at index 7: (good: `a`, bad: `n`)
bad string contains extra characters: `abc`
thread 'tests::test_str_comp' panicked at 'assertion failed: false', src/lib.rs:52:9
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.


failures:
    tests::test_str_comp