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/