来自原始 http 数据的 C++ 中的 nLohmann lib
nLohmann lib in C++ from raw http data
我有原始的 http 数据
char text[] = R"({\"ID\": 123,\"Name\": \
"Afzaal Ahmad Zeeshan\",\"Gender\":
true, \"DateOfBirth\": \"1995-08-29T00:00:00\"})";
我正在使用 Json nlohmann lib,它给我解析错误,如果我尝试以下操作,它会解析
R"({"happy": true, "pi": 3.141})"
难道nlohmann没有解析http原始数据?
您使用的是原始字符串文字,因此请删除反斜杠:
char text[] = R"({
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan",
"Gender": true,
"DateOfBirth": "1995-08-29T00:00:00"
})";
完整示例:
#include <nlohmann/json.hpp>
#include <iomanip>
#include <iostream>
using json = nlohmann::json;
int main() {
char text[] = R"({
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan",
"Gender": true,
"DateOfBirth": "1995-08-29T00:00:00"
})";
char text2[] = R"({"happy": true, "pi": 3.141})";
json obj1, obj2;
try {
obj1 = json::parse(text);
obj2 = json::parse(text2);
// print the json objects:
std::cout << std::setw(2) << obj1 << '\n'
<< obj2 << '\n';
}
catch(const json::parse_error& ex) {
std::cerr << "parse error at byte " << ex.byte << std::endl;
}
}
可能的输出:
{
"DateOfBirth": "1995-08-29T00:00:00",
"Gender": true,
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan"
}
{"happy":true,"pi":3.141}
我有原始的 http 数据
char text[] = R"({\"ID\": 123,\"Name\": \
"Afzaal Ahmad Zeeshan\",\"Gender\":
true, \"DateOfBirth\": \"1995-08-29T00:00:00\"})";
我正在使用 Json nlohmann lib,它给我解析错误,如果我尝试以下操作,它会解析
R"({"happy": true, "pi": 3.141})"
难道nlohmann没有解析http原始数据?
您使用的是原始字符串文字,因此请删除反斜杠:
char text[] = R"({
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan",
"Gender": true,
"DateOfBirth": "1995-08-29T00:00:00"
})";
完整示例:
#include <nlohmann/json.hpp>
#include <iomanip>
#include <iostream>
using json = nlohmann::json;
int main() {
char text[] = R"({
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan",
"Gender": true,
"DateOfBirth": "1995-08-29T00:00:00"
})";
char text2[] = R"({"happy": true, "pi": 3.141})";
json obj1, obj2;
try {
obj1 = json::parse(text);
obj2 = json::parse(text2);
// print the json objects:
std::cout << std::setw(2) << obj1 << '\n'
<< obj2 << '\n';
}
catch(const json::parse_error& ex) {
std::cerr << "parse error at byte " << ex.byte << std::endl;
}
}
可能的输出:
{
"DateOfBirth": "1995-08-29T00:00:00",
"Gender": true,
"ID": 123,
"Name": "Afzaal Ahmad Zeeshan"
}
{"happy":true,"pi":3.141}