簡體   English   中英

使用 nlohmann json 或 Rapidjson 解析 libcurl 響應

[英]parse libcurl responce with nlohmann json or rapidjson

我的 libcurl 代碼返回我的 json 字符串:

{"object":"user","attributes":{"id":000,"admin":false,"username":"un","email":"google@gmail.com","first_name":"leopold95","last_name":"leopold95","language":"en"}}

我想在我的對象中解析這個字符串(我的問題不在其中)。 但是當我嘗試用 nlohmann 或快速解析這個時,我有一個錯誤。 但是如果我嘗試解析這個字符串:

string str = "{\"object\":\"user\",\"attributes\":{\"id\":36,\"admin\":false,\"username\":\"a4qsmr9m\",\"email\":\"leopold9586@gmail.com\",\"first_name\":\"leopold95\",\"last_name\":\"leopold95\",\"language\":\"en\"}}";

使用 nlohmann 一切正常。 隨着快速,我也沒有錯誤。

所以,我的問題是:

我怎么能用 nlohmann 解析這個字符串(第一個)?

要么

我怎么能在我的回復中替換所有\\”

並且,詛咒 replace(s, "", ""); 替換(s, '', ''); , 替換(s.begin(), s.end(), ""/'', ""/''); 不要為我工作。 在某些情況下,我在字符串的末尾有我的“替換符號”

如果您需要,我可以添加更多代碼或將項目發布到 git

編輯:

UserInfo Engine::testIU(string link)
{
    CURL* curl;
    CURLcode res;

    string readBuffer;

    curl = curl_easy_init();

    struct curl_slist* headers = NULL; //headers struct
    if (curl) {
        //headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Accept: application/json");
        headers = curl_slist_append(headers, "Authorization: Bearer imr8VuU9L6qUTjyZQ0srCNyfFE7Ru0v8VOLZBMd8bhjxJFfP");

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); //add headers
        curl_easy_setopt(curl, CURLOPT_URL, link.c_str());   //set url
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); //set http method

        //curl_easy_setopt(curl,CURLOPT_RETURNTR, true);

        //curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &readBuffer); /* data goes here */

        res = curl_easy_perform(curl);

        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }

    json j = json::parse(readBuffer);

    testUserI.id = j["attributes"]["id"].get<int>();
    testUserI.admin = j["attributes"]["admin"].get<bool>();
    testUserI.username = j["attributes"]["username"].get<string>();
    testUserI.email = j["attributes"]["email"].get<string>();


    return testUserI;
}


struct UserInfo
{
    int id = 0;
    bool admin = NULL;
    string username = "";
    string email = "";
    string first_name = "";
    string last_name = "";
};
{"object":"user","attributes":{"id":0,"admin":false,"username":"a4qsmr9m","email":"google@gmail.com","first_name":"leopold95","last_name":"leopold95","language":"en"}}

編輯2:所以如果你有同樣的問題,只需在你的代碼中解決這個問題:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);

curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

並看到上面的答案和那里的所有commets

你得到的json.exception.parse_error是因為"id":000不是有效的 JSON。 它最有可能是"id":0

解決這個問題的正確方法是要求另一端糾正錯誤。

我怎么能在我的回復中替換所有"\\"

這無濟於事,實際上會使 JSON 更加無效。 初始化str中的\\不會成為字符串的一部分,您認為有效的唯一原因是該字符串中的id字段"id":36有效的。 "id":000替換它,你會看到它也無法解析。

關於添加的curl代碼的注釋。 以下不正確,會導致未定義的行為:

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &readBuffer);

CURLOPT_POSTFIELDS的參數應該是char* ,而不是std::string* 如果您不使用該選項進行發布,請刪除該選項。

您需要通過CURLOPT_WRITEDATA提供std::string*並將其轉換回CURLOPT_WRITEFUNCTION回調中的std::string&

例子:

size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
    std::string& buf = *static_cast<std::string*>(userdata);
    buf.append(ptr, std::next(ptr, nmemb * size));
    return nmemb * size;
}

curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);

對於測試,您不必使用反斜杠轉義所有" ,只需使用原始字符串文字即可。

示例:(將"id":000更改為"id":0就可以了)

#include <nlohmann/json.hpp>

#include <iostream>
#include <string>

using json = nlohmann::json;

int main() {
    std::string str =
        R"aw({"object":"user","attributes":{"id":000,"admin":false,"username":"un","email":"google@gmail.com","first_name":"leopold95","last_name":"leopold95","language":"en"}})aw";
    try {
        auto j = json::parse(str);
        std::cout << j.dump(2) << '\n';
    } catch(const json::exception& ex) {
        std::cerr << "Parse error: " << ex.what() << '\n';
    }
}

輸出:
Parse error: [json.exception.parse_error.101] parse error at line 1, column 38: syntax error while parsing object - unexpected number literal; expected '}'

修復了錯誤的輸出:

{
  "attributes": {
    "admin": false,
    "email": "google@gmail.com",
    "first_name": "leopold95",
    "id": 0,
    "language": "en",
    "last_name": "leopold95",
    "username": "un"
  },
  "object": "user"
}

在您編輯的問題中輸入:

std::string str =
    R"aw({"object":"user","attributes":{"id":36,"admin":false,"username":"a4qsmr9m","email":"leopold9586@gmail.com","first_name":"leopold95","last_name":"leopold95","language":"en"}})aw";

它將被成功解析,上面的程序將打印:

{
  "attributes": {
    "admin": false,
    "email": "leopold9586@gmail.com",
    "first_name": "leopold95",
    "id": 36,
    "language": "en",
    "last_name": "leopold95",
    "username": "a4qsmr9m"
  },
  "object": "user"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM