我正在嘗試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。
關于如何進行的任何建議?我對這個庫的嘗試是否合理?
uj5u.com熱心網友回復:
正如 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>,
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477183.html
標籤:json 锈 serde-json
