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

允我心安 提交于 2019-12-07 22:04:42

问题


How to use json-spirit to read json string in C++? I read the demo code. I find that:

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" } };

Can I convert a String into a json object?

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

回答1:


json_spirit provides bool read_string( const String_type& s, Value_type& value ) and bool read( const std::string& s, Value& value ) to read json data from strings.

Here is an example:

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;
      }
    }
}

You could also use ifstream instead of string to read from json from file.

Please note, according to RFC4627 a string begins and ends with quotation marks.



来源:https://stackoverflow.com/questions/16827508/using-json-spirit-to-read-json-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!