好的,所以我从客户端获取了这个JSON对象:
{"command":"BrugerIndtastTF","brugerT":"\"10\"","brugerF":"\"20\""}
然后,我需要使用“ brugerT”中的int值,但是如您所见,它的周围带有“ \” 10 \””。当我用javascript编写代码时,我没有遇到这个问题。有没有办法只使用“ brugerT”中表示10的部分?
仅* temp的代码应打印int值10:
socket_->hub_.onMessage([this](
uWS::WebSocket<uWS::SERVER> *ws,
char* message,
size_t length,
uWS::OpCode opCode
)
{
std::string data = std::string(message,length);
std::cout << "web::Server:\t Data received: " << data << std::endl;
// handle manual settings
std::cout << "Web::Server:\t Received request: manual. Redirecting message." << std::endl;
json test1 = json::parse(data);
auto test2 = test1.json::find("command");
std::cout << "Web::Server:\t Test 1" << test1 << std::endl;
std::cout << "Web::Server:\t Test 2" << *test2 << std::endl;
if (*test2 =="BrugerIndtastTF")
{
std::cout<<"Web::Server:\t BrugerIndtastTF modtaget" << std::endl;
auto temp= test1.json::find("brugerT");
auto humi= test1.json::find("brugerF");
std::cout << "Web::Server:\t temp: " << *temp << "humi: " << *humi << std::endl;
}
});
编辑: Here you can see the terminal
它应该说:temp:10 humi:20
答案 0 :(得分:1)
您可以尝试获取string
的{{1}}值,并从字符串中去除brugerT
,然后将生成的\"
转换为string
与stoi
。您甚至可以使用正则表达式在int
内查找整数,然后让该库找出最佳匹配方法。正则表达式将类似于:string
ps字符串literal type 6可能在手动滤除([0-9]+)
\"
答案 1 :(得分:0)
提供此数据
https://pde.api.here.com/1/search/proximity.json?app_code={{app_code}}&app_id={{app_id}}&layer_ids=LINK_FC1&proximity=29.680334933229688,-95.39327178890237,100&key_attributes=LINK_ID
使用nlohmann:
const std::string data = R"({"command":"BrugerIndtastTF","brugerT":"\"10\"","brugerF":"\"20\""})";
输出:
using namespace nlohmann;
json j = json::parse(data);
std::string s = j["brugerT"].get<std::string>();
size_t idx = 0;
int n = std::stoi(s.c_str()+1, &idx);
std::cout << "n: " << n << "\n";
使用jsoncons:
n: 10
输出:
using namespace jsoncons;
json j = json::parse(data);
int n = json::parse(j["brugerT"].as<std::string>()).as<int>();
std::cout << "n: " << n << "\n";
通常,nlohmann不会将字符串转换为n: 10
,如果在字符串上调用int
,它将失败。因此,您需要获取字符串,然后将其转换为get<int>()
自己使用int
。在您的情况下,该字符串在数字周围嵌入了引号,因此执行转换时需要跳过第一个字符(引号)。
jsoncons会将带有数字的字符串转换为stoi
,但不能将带有
嵌入引号,因此在该示例中,我们分析了字符串的(引号)内容以将其删除。