问题描述
我正在使用 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;
我想返回我的名字,任何人都可以帮我解决这个问题。提前致谢
解决方法
我在 crow 中将 JSON 用于现代 C++ (https://github.com/nlohmann/json) 这是我写的一个例子 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 的东西。将其添加到第 7215 行的 struct response
部分
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");
}
}