【发布时间】:2021-11-26 14:06:57
【问题描述】:
我从以下格式的服务器收到 json 响应:
{"value": 98.3}
但有些情况下,响应可能是:
{"value": null}
我编写了一个 C++ 程序,它使用 boost json 来解析它并获取浮点值
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace pt = boost::property_tree;
int main(int argc, char **argv)
{
try
{
float valuef;
pt::ptree root;
std::stringstream ss;
string result;
std::ifstream file("test.json");
if (file)
{
ss << file.rdbuf();
file.close();
}
pt::read_json(ss, root);
auto value = root.get<string>("value");
if (value != "null")
{
valuef = stof(value);
}
cout <<"float value is" << valuef << endl;
}
catch (std::exception &e)
{
string err = e.what();
cout << "error is " << endl
<< err << endl;
}
}
所以我总是检查该值是否与文字“null”不相等,因为根据此
Boost Json with null elements
不支持输出空值。
由于这篇文章已有 7 年的历史,我想知道最新的 boost 库是否支持更通用的东西来检查空值?
【问题讨论】: