我正在尝试serde_json
在 Rust 中使用以下松散格式解析 JSON 文件:
{
"Source_n": {
"Destination_n": {
"distance": 2,
"connections": [
{
"color": "Any",
"locomotives": 0,
"tunnels": 0
}
]
}
...
whereSource
并且Destination
可以是任意数量的键(链接到完整文件)。
我创建了以下结构以尝试对 JSON 进行反序列化:
#[derive(Debug, Deserialize)]
struct L0 {
routes: HashMap<String, L1>,
}
#[derive(Debug, Deserialize)]
struct L1 {
destination_city: HashMap<String, L2>,
}
#[derive(Debug, Deserialize)]
struct L2 {
distance: u8,
connections: Vec<L3>,
}
#[derive(Debug, Deserialize, Clone)]
struct L3 {
color: String,
locomotives: u8,
tunnels: u8,
}
当我尝试将 JSON 作为 L0 对象读取时,我对这一行感到恐慌:
let data: L0 = serde_json::from_str(&route_file_as_string).unwrap();
恐慌:
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/ticket-to-ride`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("missing field `routes`", line: 1889, column: 1)', src/route.rs:39:64
stack backtrace:
0: rust_begin_unwind
at /rustc/59eed8a2aac0230a8b53e89d4e99d55912ba6b35/library/std/src/panicking.rs:517:5
1: core::panicking::panic_fmt
at /rustc/59eed8a2aac0230a8b53e89d4e99d55912ba6b35/library/core/src/panicking.rs:101:14
2: core::result::unwrap_failed
at /rustc/59eed8a2aac0230a8b53e89d4e99d55912ba6b35/library/core/src/result.rs:1617:5
3: core::result::Result<T,E>::unwrap
at /rustc/59eed8a2aac0230a8b53e89d4e99d55912ba6b35/library/core/src/result.rs:1299:23
4: ticket_to_ride::route::route_file_to_L0
at ./src/route.rs:39:20
5: ticket_to_ride::route::routes_from_file
at ./src/route.rs:44:33
6: ticket_to_ride::main
at ./src/main.rs:6:5
7: core::ops::function::FnOnce::call_once
at /rustc/59eed8a2aac0230a8b53e89d4e99d55912ba6b35/library/core/src/ops/function.rs:227:5
我已经能够将 JSON 作为HashMap<String, Value>
对象读取,但是每当我尝试在较低级别开始工作时,都会出现错误。它似乎在寻找一个名为 的键routes
,但我实际上想要的是一个嵌套的 HashMap,类似于您如何以嵌套方式在 Python 中读取 JSON。
关于如何进行的任何建议?我对这个库的尝试是否合理?
正如 Sven Marnach 在他们的评论中所说,添加#[serde(flatten)]
以从使用键作为 JSON 字段的数据创建 HashMap:
#[derive(Debug, Deserialize)]
struct L0 {
#[serde(flatten)]
routes: HashMap<String, L1>,
}
#[derive(Debug, Deserialize)]
struct L1 {
#[serde(flatten)]
destination_city: HashMap<String, L2>,
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句