首页 > 解决方案 > 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,
}
}

标签: rustdeserializationjson-deserializationserdereqwest

解决方案


Deserialize结构上的派生Slice不适用于 JSON 数组,而是需要带有 fields 的 JSON 字典data1data2依此类推。大概,您不想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),
}

使用枚举,不再需要类型参数Ton ,您可以使用:AllData

#[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


推荐阅读