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

标签 c++ json json-spirit

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 从文件中读取 json。

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

关于c++ - C++中使用json-spirit读取json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16827508/

相关文章:

c++ - vector 内存的有效清除

c++ - 通过 vertex_index 属性访问顶点?

jquery - 发送 JSON 数据到服务器错误

ruby-on-rails - Rails 无法正确呈现来自 Postgres JSON 函数的嵌套 JSON 结果

android - ionic 使用 $cordovaFile 读取本地 json 文件

c++ - 如何用json精神读取递归json数据

c++ - 将 protobuf 字节类型存储在二进制文件中

c++ - 使用 OpenCV 作为机器学习库而不是 TensorFlow?