gpt4 book ai didi

rust - 如何正确导入 serde_with::nested::json 依赖项

转载 作者:行者123 更新时间:2023-12-03 11:45:31 26 4
gpt4 key购买 nike

我正在尝试使用此处 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());
}

关于rust - 如何正确导入 serde_with::nested::json 依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61967401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com