boost::json:如何检查值是否存在并具有特定类型
在 boost::json 中有两种方法检查值是否存在并具有特定类型。请参见下面的完整示例,你可以在其中测试两种方法。我通常推荐选项 1,因为 100% 正确地进行所有检查很繁琐,而且人们往往容易忘记一些边缘情况。
仅对于禁用异常的嵌入式系统(并且启用异常不是一个选项),选项 2 是正确的方法。
选项 1:捕获异常
check_value.cpp
void extractTimestamp(const boost::json::value& jv) {
try {
double timestamp = jv.as_object().at("timestamp").as_double();
std::cout << "Timestamp: " << timestamp << std::endl;
} catch (const boost::system::system_error& e) {
std::cerr << "Error" << e.code() << ": " << e.what() << std::endl;
}
}选项 2:使用显式检查
check_value_explicit.cpp
void extractTimestamp2(const boost::json::value& jv) {
// Extract the timestamp as a double
if (jv.is_object() && jv.as_object().contains("timestamp")) {
double timestamp = jv.as_object().at("timestamp").as_double();
std::cout << "Timestamp: " << timestamp << std::endl;
} else {
std::cerr << "Error: 'timestamp' field is missing in the JSON data." << std::endl;
}
}完整测试用例
check_value_test.cpp
#include <boost/json.hpp>
#include <iostream>
// TODO: Insert one of the extractTimestamp functions here!
int main() {
// Test with correct JSON
{
std::string line = "{\"timestamp\":1675910171.91}";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
// Test with incorrect JSON #1
{
std::string line = "{}";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
// Test with incorrect JSON #2
{
std::string line = "[]";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
return 0;
}选项 1 的输出:
output_option1.txt
Timestamp: 1.67591e+09
Error boost.json:17: out of range [boost.json:17 at /usr/include/boost/json/impl/object.hpp:388 in function 'at']
Error boost.json:31: value is not an object [boost.json:31 at /usr/include/boost/json/value.hpp:2529 in function 'as_object']选项 2 的输出:
注意这里的错误消息不是很具体。
output_option2.txt
Timestamp: 1.67591e+09
Error: 'timestamp' field is missing in the JSON data.
Error: 'timestamp' field is missing in the JSON data.If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow