我很难将 Rust reqwests::response 反序列化为 json

问题描述 投票:0回答:1

我正在构建一个通过 oauth2 进行身份验证的网络服务器。通过 axum/oauth 的示例,我让它与我的 nextcloud-instance 一起使用。为了获取 UserId 并将其存储在数据库中,我想从 nextcloud 实例向 OCS-Api 发出请求。该请求有效,我得到了预期的响应,但无法将其序列化。这是 OCS-Api 文档,其中包含预期的响应示例。

{
  "ocs": {
    "meta": {
      "status": "string",
      "statuscode": 0,
      "message": "string",
      "totalitems": "string",
      "itemsperpage": "string"
    },
    "data": {
      "userId": "string",
      "message": "string",
      "icon": "string",
      "clearAt": 0,
      "status": "online",
      "messageId": "string",
      "messageIsPredefined": true,
      "statusIsUserDefined": true
    }
  }
}

https://docs.nextcloud.com/server/latest/developer_manual/_static/openapi.html#/operations/user_status-user_status-get-status

我尝试将响应中的 Json 序列化到我的 OCSUser 结构中

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OCSUser {
    user_id: String,
}

这是有问题的函数:

let token = oauth_client
        .exchange_code(AuthorizationCode::new(query.code.clone()))
        .request_async(async_http_client)
        .await
        .context("failed in sending request request to authorization server")?;

    // Fetch user data from discord
    let client = reqwest::Client::new();
    let client2 = client
        // https://discord.com/developers/docs/resources/user#get-current-user
        .get("https://nextcloud.apo-riesinger.de/ocs/v2.php/apps/user_status/api/v1/user_status")
        .bearer_auth(token.access_token().secret())
        .header("OCS-APIREQUEST", "true")
        .header(ACCEPT, "application/json")
        .send()
        .await
        .context("failed in sending request to target Url")?;
    println!("{:?}", &client2);
    let user_data = client2
        .json::<OCSUser>()
        .await
        .context("failed to deserialize response as JSON")?;
    println!("{:?}", &user_data);

总是到达&client2的打印语句,但无法到达最后一条。 为了测试水域,我尝试根据文档对预期响应的结构进行建模,并通过 Structure 的文本方法获得输出。 输出如下

"{\"ocs\":{\"meta\":{\"status\":\"ok\",\"statuscode\":200,\"message\":\"OK\"},\"data\":{\"userId\":\"chef\",\"message\":null,\"messageId\":null,\"messageIsPredefined\":false,\"icon\":null,\"clearAt\":null,\"status\":\"offline\",\"statusIsUserDefined\":false}}}"

我最后的想法是文本编码不同,但我不确定。 为了完整起见,这里是 client2 的打印语句的内容

Response { url: Url { scheme: "https", cannot_be_a_base: false, username: "", password: None, host: Some(Domain("nextcloud.apo-riesinger.de")), port: None, path: "/ocs/v2.php/apps/user_status/api/v1/user_status", query: None, fragment: None }, status: 200, headers: {"server": "openresty", "date": "Wed, 24 Jan 2024 23:51:35 GMT", "content-type": "application/json; charset=utf-8", "content-length": "223", "connection": "keep-alive", "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", "x-frame-options": "SAMEORIGIN", "x-permitted-cross-domain-policies": "none", "x-robots-tag": "noindex, nofollow", "x-xss-protection": "1; mode=block", "x-powered-by": "PHP/8.2.15", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc_sessionPassphrase=FhePXWSLltK4IXpDmcTi%2Fk0pT%2FDEcDRXQjW%2Fu1jcew%2BjvxiUeEnMQl11pRIRNDq3nHncV6xcDLJ26zNR2%2BStn1dcx%2F684OWV6tzK0Dg92Hxg%2BxjCMDbxAShCWB9Mmp5O; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "__Host-nc_sameSiteCookielax=true; path=/; httponly;secure; expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=lax", "set-cookie": "__Host-nc_sameSiteCookiestrict=true; path=/; httponly;secure; expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=strict", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "set-cookie": "oc5ny1g9qec3=53d44aaeaa6fd48dccad3e27f7525d44; path=/; secure; HttpOnly; SameSite=Lax", "expires": "Thu, 19 Nov 1981 08:52:00 GMT", "cache-control": "no-cache, no-store, must-revalidate", "pragma": "no-cache", "content-security-policy": "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'", "x-request-id": "F1j2zkPIca8Z5fS66ktF", "feature-policy": "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'", "strict-transport-security": "max-age=63072000; preload", "x-served-by": "nextcloud.apo-riesinger.de"} }

由于这是我的第一个 Rust 项目,我非常感谢您的帮助。这是一门非常困难但相当有益的语言。 有人有想法吗?非常感谢。

json rust response serde reqwest
1个回答
0
投票

您的结构需要包含与 JSON 相同的嵌套结构。

#[derive(Debug, Serialize, Deserialize)]
struct OCSUser {
    ocs: Ocs,
}

#[derive(Debug, Serialize, Deserialize)]
struct Ocs {
    data: OcsData,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OcsData {
    user_id: String,
}
© www.soinside.com 2019 - 2024. All rights reserved.