如何正确导入 serde_with::nested::json 依赖项
How to get serde_with::nested::json dependency imported properly
我正在尝试使用此处 serde_with 文档中概述的设置将嵌套的 json 反序列化到我的结构中:https://docs.rs/serde_with/1.4.0/serde_with/json/nested/index.html
几次尝试后 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 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_with
不是可选的,必须提供功能 json
。
替换
serde_with = { version = "1.4.0", optional = true}
和
serde_with = { version = "1.4.0", features = ["json"]}
完整示例:
Cargo.toml
[dependencies]
serde = { version = "1.0" }
serde_json = "1.0"
serde_derive = "1.0"
serde_with = { version = "1.4.0", features = ["json"]}
main.rs
#[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());
}
我正在尝试使用此处 serde_with 文档中概述的设置将嵌套的 json 反序列化到我的结构中:https://docs.rs/serde_with/1.4.0/serde_with/json/nested/index.html
几次尝试后 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 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_with
不是可选的,必须提供功能 json
。
替换
serde_with = { version = "1.4.0", optional = true}
和
serde_with = { version = "1.4.0", features = ["json"]}
完整示例:
Cargo.toml
[dependencies]
serde = { version = "1.0" }
serde_json = "1.0"
serde_derive = "1.0"
serde_with = { version = "1.4.0", features = ["json"]}
main.rs
#[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());
}