2013-05-30 38 views
1

如何使用json-spirit讀取C++中的json字符串?我閱讀演示代碼。 我發現:使用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" } }; 

我可以將一個字符串轉換成JSON對象?

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

回答

7

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的而不是字符串從JSON從文件中讀取。

請注意,根據RFC4627,字符串以引號開頭和結尾。