我正在尝试使用 simdjson 库:https://github.com/simdjson/simdjson#documentation
但是,我需要解析的 json 通过 websocket 连接传输,并且并不总是包含相同的键。因此,有时尝试从解析的 json 对象中按键提取值会引发异常:
terminate called after throwing an instance of 'simdjson::simdjson_error'
what(): The JSON field referenced does not exist in this object.
Aborted (core dumped)
下面尝试使异常处理起作用的示例代码:
#include <iostream>
#include <string>
#include <chrono>
#include "simdjson.h"
using namespace std;
using namespace simdjson;
int main() {
auto cars_json = R"( [
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
] )"_padded;
simdjson::error_code error_c;
dom::parser parser;
dom::object doc;
dom::element elem;
const char* value;
doc = parser.parse(cars_json);
try
{
doc["clOrdID"].get<const char*>().tie(value, error_c);
}
catch (simdjson_error e)
{
cout << 1 << endl;
}
return 0;
}
我在这里阅读了有关库错误处理的文档: https://github.com/simdjson/simdjson/blob/master/doc/basics.md#error-handling
但是,使用 try-catch block 和上面文档中描述的错误处理方法仍然会导致程序退出。我对 C++ 编程非常陌生,因此对该语言的异常处理也很陌生 - 任何有关如何从该库捕获任何异常的指导将不胜感激!
最佳答案
首先,您应该将 parser.parse(cars_json);
移动到 try/catch
block 中,以便捕获解析器异常
try {
doc = parser.parse(cars_json);
} catch (simdjson::simdjson_error e) {
cout << e.what() << endl;
}
那么您可能会意识到解析器
不会返回simdjson::dom::object
而是simdjson::dom::array
相反。
这里是转换为 const char*
的更新示例
const char* value;
try {
auto root = parser.parse(cars_json);
cout << "root: " << root.type() << endl;
auto car = root.at(0);
if(car["make"].is_string()){
cout << "first car: " << car["make"] << endl;
}
//check non-existing element
if(car["foo"].is_string()){
// exception won't be thrown
}
std::string_view sv = root.at(1)["model"];
cout << "string view: " << sv << endl;
//conversion to const char*
value = std::string(sv).c_str();
cout << "const char: " << value << endl;
} catch (const simdjson::simdjson_error &e) {
cout << e.what() << endl;
}
输出应该是:
root: array
first car: "Toyota"
string view: Soul
const char: Soul
关于simdjson 库未捕获 C++ 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62245390/