rust - Rust - 使用 serde/reqwest “无效类型”进行反序列化
问题描述
我正在尝试反序列化以下 API 响应(为简单起见,我只会复制数组的两个切片,但实际上它会更大)。代码被过度简化以演示示例。
API 响应:
[[1609632000000,32185,32968,34873,31975,18908.90248876],[1609545600000,29349.83250154,32183,33292,29000,22012.92431526]]
所以它是一个大数组/向量,由具有六个整数或浮点数的数组/向量组成(它们的位置也会有所不同)。
为此,我正在尝试使用 generics ,但似乎我遗漏了一些东西,因为我无法编译它。
它失败了
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: reqwest::Error { kind: Decode, source: Error("invalid type: integer `1609632000000`, expected struct T", line: 1, column: 15) }'
use blocking::Response;
use serde::{Deserialize, Serialize};
use reqwest::{blocking, Error, StatusCode};
struct allData<T> {
data: Slice<T>
}
#[derive(Debug, Serialize, Deserialize)]
struct Slice<T>{
data1: T,
data2: T,
data3: T,
data4: T,
data5: T,
data6: T,
}
fn get_data() -> Option<Slice> /*I know the signature is not correct, read until the end for the correct one*/ {
let url = format!("{}", my_url_string);
let response: Slice<T> = blocking::get(&url).unwrap().json().unwrap();
Some(response);
}
fn main() {
let call_the_api = get_data();
println!("{:?}", call_the_api);
}
将 Struct 与可以返回“切片”向量的泛型一起使用的正确方法是什么。
IE。
Vector{
Slice {
data1,
data2,
data3,
data4,
data5,
data6,
},
Slice {
data1,
data2,
data3,
data4,
data5,
data6,
}
}
解决方案
Deserialize
结构上的派生Slice
不适用于 JSON 数组,而是需要带有 fields 的 JSON 字典data1
,data2
依此类推。大概,您不想Deserialize
为您的类型手动实现特征,因此您需要 aVec<Vec<T>>
来为嵌套数组建模:
#[derive(Deserialize)]
#[serde(transparent)]
struct AllData<T>(Vec<Vec<T>>);
此类型将 中的所有项目限制Vec
为 type T
。这意味着,你不能使用 somef64
和 some i64
,它要么是浮点数,要么是整数。要使这个包装器对浮点数和整数都通用,您可能需要一些枚举:
#[derive(Deserialize)]
// note, this causes deserialization to try the variants top-to-bottom
#[serde(untagged)]
enum FloatOrInt {
Int(i64),
Float(f64),
}
使用枚举,不再需要类型参数T
on ,您可以使用:AllData
#[derive(Deserialize)]
#[serde(transparent)]
struct AllData(Vec<Vec<FloatOrInt>>);
如果您确定内部数组的长度始终为 6,则可以将其替换为数组:[FloatOrInt; 6]
。
把它放在一起,你会得到这样的东西:
推荐阅读
- kubernetes-helm - 如何控制伞形图中 helm 子图的安装顺序
- pdftron - 如何在 XamarinForms Pdftron 中使用 ToolManagerBuilder 设置 ToolManager 只读模式
- javascript - Flatlist、React Native 的扁平化数组
- c++ - 在 FreeBSD 中,clang 找不到标准 c++ 库头文件
- python - 如何永久设置 LD_LIBRARY_PATH
- sass - Svelte Materialify 库不加载主题样式
- c++ - 非常量复制构造函数可以用 C++17 编译
- python - Python QRCODE 保存到文件夹
- reactjs - 反应静态文件不在html内呈现
- php - 我无法获取系统的当前时间