【问题标题】:Serde JSON from Struct Example Not Working结构示例中的 Serde JSON 不起作用
【发布时间】:2020-12-17 17:29:03
【问题描述】:

我似乎无法获得提供的example 使用 serde 序列化结构的工作。我正在为我的Address 结构实现特征Serialize,但是我收到一个编译错误,表明这个特征没有实现。我做错了什么?

[dependencies]
serde = "1.0.118"
serde_json = "1.0.60"
use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}
fn main(){
    print_an_address();
}

fn print_an_address() -> Result<()> {
    // Some data structure.
    let address = Address {
        street: "10 Downing Street".to_owned(),
        city: "London".to_owned(),
    };

    // Serialize it to a JSON string.
    let j = serde_json::to_string(&address)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}
error[E0277]: the trait bound `Address: Serialize` is not satisfied
    --> src\main.rs:21:35
     |
21   |     let j = serde_json::to_string(&address)?;
     |                                   ^^^^^^^^ the trait `Serialize` is not implemented for `Address`
     | 
    ::: C:\Users\Primary User\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.60\src\ser.rs:2221:17
     |
2221 |     T: ?Sized + Serialize,
     |                 --------- required by this bound in `serde_json::to_string`

【问题讨论】:

标签: rust serde


【解决方案1】:

您需要在Cargo.toml 中为serde 指定derive 功能。

serde = { version = "1.0.118", features = ["derive"] }

更多信息请参见:https://serde.rs/derive.html

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多