0

我正在使用 cpp crow 库,我在访问单个对象时遇到困难,我在此处附加我的代码。

CROW_ROUTE(app,"/hello/<string>")
([](string name){
    crow::json::wvalue x;
  x["name"] = "llllds";
  x["Town"] = "Texas";
  x["nickname"] = "drax";
  x["father"] = "Nethan";
  
  if (name == "Nothing")
       cout << "Bad Responce";
    std::ostringstream os;
   cout << name << " is the required query";
   val = x[name];
   return val;

我想返回我的名字,任何人都可以帮我解决这个问题。提前致谢

4

1 回答 1

0

我在 crow ( https://github.com/nlohmann/json ) 中将JSON 用于 Modern C++。这是我写的一个示例 CROW_ROUTE

CROW_ROUTE(app, "/palindromes/<string>/<string>")([](const request &req, response &res, string ID, string words){
    palindromeHash.insert({ID, words}); //ignore this
    nlohmann::json x;
    x = getPalindromes(palindromeHash.at(ID));
    palindromeHash.erase(ID); //ignore this
    res.sendJSON(x);
});

//getPalindromesFunction()

nlohmann::json getPalindromes(string data){
    nlohmann::json x;
    unordered_map<string, bool> hashmap;
    string word = "";
    std::string::size_type i = data.find("%20");
    while (i != std::string::npos){
        data.erase(i, 3);
        data.insert(i, " ");
        i = data.find("%20", i);
    }
    for(int i = 0; i < data.size(); i++){
        if(data[i] == ' '){
            hashmap.insert({word, true});
            word = "";
        }
        else{
            word += data[i];
        }
    }
    string temp;
    vector<string> words;
    int numValid = 0;
    for(auto& i: hashmap){
        temp = i.first;
        reverse(temp.begin(), temp.end());
        auto got = hashmap.find(temp);
        if(got != hashmap.end()){
            words.push_back(i.first);
            numValid++;
        }
    }
    x["words"] = words;
    x["numValid"] = numValid;
    return x;
}

如您所见,它返回一个包含回文的 JSON 对象 x。sendJSON() 函数是我添加到 crow_all.h 中的。将其添加到struct response第 7215 行的部分下

void sendJSON(const nlohmann::json& data){
    std::string response = data.dump();

    add_header("Access-Control-Allow-Origin", "*");
    add_header("Content-Type", "text/html");
    write(response);
    end();
}

请记住在 main.cpp 和 crow_all.h 中都包含“json.h”。res.sendJSON 会将其发送到我的 JS 文件,该文件可以轻松地循环遍历 JSON。

$.get("/palindromes/" + ID + "/" + curr_line, {}, function(response){
        let x = JSON.parse(response); //This will allow JS to read the C++ JSON
        for(let i = 0; i < x.words.length; i++){
            term.write(x.words[i] + "\r\n");
        }
}
于 2021-05-18T23:58:59.733 回答