Вопрос

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'}";
Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top