在c++中使用json-spirit读取json字符串

Using json-spirit to read json string in C++

本文关键字:读取 json 字符串 json-spirit c++      更新时间:2023-10-16

如何在c++中使用json-spirit读取json字符串?我读了演示代码。我发现:

const Address addrs[5] = { { 42, "East Street",  "Newtown",     "Essex",         "England" },
                               { 1,  "West Street",  "Hull",        "Yorkshire",     "England" },
                               { 12, "South Road",   "Aberystwyth", "Dyfed",         "Wales"   },
                               { 45, "North Road",   "Paignton",    "Devon",         "England" },
                               { 78, "Upper Street", "Ware",        "Hertfordshire", "England" } };

我可以将字符串转换为json对象吗?

char* jsonStr = "{'name', 'Tom'}";

json_spirit提供bool read_string( const String_type& s, Value_type& value )bool read( const std::string& s, Value& value )从字符串中读取json数据。

下面是一个例子:

string name;
string jsonStr("{"name":"Tom"}");
json_spirit::Value val;
auto success = json_spirit::read_string(jsonStr, val);
if (success) {
    auto jsonObject = val.get_obj();
    for (auto entry : jsonObject) {
      if (entry.name_ == "name" && entry.value_.type() == json_spirit::Value_type::str_type) {
        name = entry.value_.get_str();
        break;
      }
    }
}

你也可以用ifstream代替string从file中读取json。

请注意,根据RFC4627,字符串以引号开始和结束。