如何使用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" } };
我可以将String转换为json对象吗?
char* jsonStr = "{'name', 'Tom'}";
答案 0 :(得分: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;
}
}
}
您也可以使用ifstream而不是string来从文件中读取json。
请注意,根据RFC4627,字符串以引号开头和结尾。