Rust - 使用serde/reqwest进行反序列化时出现“无效类型”

5

我正在尝试对以下API响应进行反序列化(为简单起见,我只复制了数组的两个片段,但实际上它会更大)。 代码过于简化,仅演示示例。

API响应:

[[1609632000000,32185,32968,34873,31975,18908.90248876],[1609545600000,29349.83250154,32183,33292,29000,22012.92431526]]

因此,这是由数组/向量组成的大型数组/向量,其包含六个整数或浮点数(它们的位置也会变化)。

为此,我尝试使用泛型,但似乎我错过了某些东西,因为我无法使其编译通过..

它会失败并显示如下错误信息:

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);
}

如何正确使用带有泛型的结构体,以返回“Slice”向量。

例如:

Vector{
    Slice {
     data1,
     data2,
     data3,
     data4,
     data5,
     data6,
},
    Slice {
      data1, 
      data2,
      data3,
      data4,
      data5,
      data6,
}
}
1个回答

3
你的 Slice 结构体上的 Deserialize 派生无法用于 JSON 数组,而是期望一个包含字段 data1data2 等的 JSON 字典。你可能不想手动实现你的类型的 Deserialize 特征,因此你需要一个 Vec<Vec<T>> 来模拟嵌套数组:
#[derive(Deserialize)]
#[serde(transparent)]
struct AllData<T>(Vec<Vec<T>>);

这种类型将Vec中的所有项目都限制为T类型。这意味着,您不能使用一些f64和一些i64,它要么全部是浮点数,要么全部是整数。要使此包装器通用于浮点数和整数,您可能需要一些枚举:

#[derive(Deserialize)]
// note, this causes deserialization to try the variants top-to-bottom
#[serde(untagged)]
enum FloatOrInt {
    Int(i64),
    Float(f64),
}

使用枚举,AllData 上的类型参数 T 不再需要,您可以采用以下方式:

#[derive(Deserialize)]
#[serde(transparent)]
struct AllData(Vec<Vec<FloatOrInt>>);

如果您确信内部数组始终具有长度为6,您可以用一个数组替换它:[FloatOrInt; 6]
将它们组合起来,您会得到类似这样的代码:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=52bd3ce7779cc9b7b152c681de8681c4


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接