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

Jef*_*Lee 2 c++ json json-spirit

如何使用json-spirit在C++中读取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" } };
Run Code Online (Sandbox Code Playgroud)

我可以将String转换为json对象吗?

char* jsonStr = "{'name', 'Tom'}";
Run Code Online (Sandbox Code Playgroud)

dnl*_*kng 8

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;
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用ifstream而不是string来从文件中读取json.

请注意,根据RFC4627,字符串以引号开头和结尾.