无法将 json 反序列化为 Rust 中的结构

Asn*_*ari 1 rust

我正在尝试将字符串反序列化为 Rust 中的结构。以下代码仅来自json_serde文档。

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

fn main() {
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into a Person object. This is exactly the
    // same function as the one that produced serde_json::Value above, but
    // now we are asking it for a Person as output.
    let p: Person = serde_json::from_str(data).expect("bal");

    // Do things just like with any other Rust data structure.
    println!("Please call {} at the number {}", p.name, p.phones[0]);


}

Run Code Online (Sandbox Code Playgroud)

上面的代码片段给了我一个错误:

   Compiling test-json-rs v0.1.0 (/Users/asnimpansari/Desktop/Personal/test-json-rs)
error: cannot find derive macro `Serialize` in this scope
 --> src/main.rs:4:10
  |
4 | #[derive(Serialize, Deserialize)]
  |          ^^^^^^^^^

error: cannot find derive macro `Deserialize` in this scope
 --> src/main.rs:4:21
  |
4 | #[derive(Serialize, Deserialize)]
  |                     ^^^^^^^^^^^

warning: unused imports: `Deserialize`, `Serialize`
 --> src/main.rs:1:13
  |
1 | use serde::{Deserialize, Serialize};
  |             ^^^^^^^^^^^  ^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `serde_json::Result`
 --> src/main.rs:2:5
  |
2 | use serde_json::Result;
  |     ^^^^^^^^^^^^^^^^^^

error[E0277]: the trait bound `Person: serde::de::Deserialize<'_>` is not satisfied
    --> src/main.rs:25:21
     |
25   |     let p: Person = serde_json::from_str(data).expect("bal");
     |                     ^^^^^^^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Person`
     | 
    ::: /Users/asnimpansari/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.55/src/de.rs:2584:8
     |
2584 |     T: de::Deserialize<'a>,
     |        ------------------- required by this bound in `serde_json::de::from_str`

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0277`.
error: could not compile `test-json-rs`.

To learn more, run the command again with --verbose.

Run Code Online (Sandbox Code Playgroud)

我的Cargo.toml文件具有以下依赖项

[dependencies]
serde_json = "1.0.55"
serde = "1.0.100"
Run Code Online (Sandbox Code Playgroud)

尽管从 struct 导入 Serialize 和 Deserializeserde并添加到 struct. 它给了我一个错误。我在这里做错了什么?

Net*_*ave 5

您需要在以下位置激活派生宏功能Cargo.toml

serde = { version = "1.0", features = ["derive"] }
Run Code Online (Sandbox Code Playgroud)