如何使用 Rust 关键字属性名称解码 JSON 对象?

How to decode JSON object with Rust keyword attribute name?

我想知道是否可以解码 Rust 中的 JSON 对象,该对象的属性名称也是 Rust 关键字。我正在使用 rustc-serialize crate,我的结构定义如下所示:

#[derive(RustcDecodable)]
struct MyObj {
  type: String
}

编译器抛出错误,因为类型是关键字。确切的编译器错误消息是:

error: expected identifier, found keyword `type`
src/mysrc.rs:23     type: String,
                           ^~~~

抱歉新手问题,我刚刚开始尝试 Rust。

您可以使用 serde crate. It supports renaming of fields since February 2015

您的示例可能如下所示:

#[derive(Deserialize)]
struct MyObj {
    #[serde(rename = "type")] 
    type_name: String
}