Rust 如何正确导入带有::nested::json依赖项的serde_
我正试图使用serde_中概述的设置和这里的文档将嵌套的json反序列化到我的结构中: 尝试几次后,Cargo.toml文件如下所示:Rust 如何正确导入带有::nested::json依赖项的serde_,rust,serde,Rust,Serde,我正试图使用serde_中概述的设置和这里的文档将嵌套的json反序列化到我的结构中: 尝试几次后,Cargo.toml文件如下所示: [dependencies] serde = { version = "1.0", features = ["derive"] } //serde_with = { version = "1.4.0", features = ["..."] } // this doesn't work even though that's what the serde_with
[dependencies]
serde = { version = "1.0", features = ["derive"] }
//serde_with = { version = "1.4.0", features = ["..."] } // this doesn't work even though that's what the serde_with README calls for
serde_with = { version = "1.4.0", optional = true }
serde_json = "1.0"
尝试上述操作时,会出现如下错误:
#[serde(default, rename(deserialize = "Plan"), with="serde_with::json::nested")]
^^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared type or module `serde_with`
我做错了什么?在您的示例中,serde_模块不是可选的,必须提供json功能 替换 serde_with={version=1.4.0,optional=true} 与 serde_with={version=1.4.0,features=[json]} 完整示例: 货舱
[dependencies]
serde = { version = "1.0" }
serde_json = "1.0"
serde_derive = "1.0"
serde_with = { version = "1.4.0", features = ["json"]}
梅因
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
#[derive(Deserialize, Serialize)]
struct A {
#[serde(with = "serde_with::json::nested")]
other_struct: B,
}
#[derive(Deserialize, Serialize)]
struct B {
value: usize,
}
fn main() {
let v: A = serde_json::from_str(r#"{"other_struct":"{\"value\":5}"}"#).unwrap();
assert_eq!(5, v.other_struct.value);
let x = A {
other_struct: B { value: 10 },
};
assert_eq!(r#"{"other_struct":"{\"value\":10}"}"#, serde_json::to_string(&x).unwrap());
}