繁体   English   中英

在 rust 中从 API 反序列化 serde_json

[英]deserializing serde_json from API in rust

我正在尝试从此端点https://prices.runescape.wiki/api/v1/osrs/latest抓取 JSON。

#[derive(Serialize, Deserialize, Debug)]
struct Latest {
    high: u32,
    highTime: String,
    low: String,
    lowTime: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct Data {
    #[serde(with = "serde_with::json::nested")]
    data: Vec<Latest>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Datav2 {
    #[serde(with = "serde_with::json::nested")]
    data: HashMap<u32, Vec<Latest>>,
}
#[cfg(not(target_arch = "wasm32"))]
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {

     let res = reqwest::get(url).await?;
    let response = &res.json::<Datav2>().await?;

}

我尝试了两个版本的数据结构。 数据使用最新的向量,但我注意到每个对象都有一个唯一的 ID,所以在 DataV2 中我尝试使用哈希图,但我得到了同样的错误。 我也尝试过不使用 Serde_with 的未嵌套版本。

我收到错误Error: reqwest::Error { kind: Decode, source: Error("invalid type: map, expected valid json object", line: 1, column: 8)

看来我的数据结构搞砸了,但已经尝试了几个小时来找出要使用的正确数据结构。

您当前的代码存在多个问题。

  1. Datav2更接近,但仍然不正确。 它不是HashMap<u32, Vec<Latest>>而是HashMap<u32, Latest> 不需要有另一个Vec ,因为每个数字都在 JSON 中分配了一个值。
  2. highTimelowlowTime不是String类型(因为它们在 JSON 中没有引号),而是无符号数字(为了安全起见,我只是假设它们是u64 )。
  3. 显然Latest的字段可以是null ,所以它们需要是Option s。
  4. 我仍然会使用snake_case作为struct中的字段名称,然后使用 serde 宏将它们重命名为camelCase

我修改了您的代码,就像我会这样做一样,以便为您提供一个如何完成的示例:

use std::collections::HashMap;

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Latest {
    high: Option<u64>,
    high_time: Option<u64>,
    low: Option<u64>,
    low_time: Option<u64>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Data {
    data: HashMap<u64, Latest>,
}

#[cfg(not(target_arch = "wasm32"))]
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let url = "https://prices.runescape.wiki/api/v1/osrs/latest";
    let res = reqwest::get(url).await?;
    let response = &res.json::<Data>().await?;

    println!("{:#?}", response);

    Ok(())
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM