描述
我们有了一个string类型的字符串,字符串是一个json串,使用C++的rapidjson库解析它
代码
按照你的需求自行更改代码,我这里只是个例子
形式1(已知大小读取内容)
string内容为
{
"store":
[
{
"grid_corners":[0,1],
"status":3
},
{
"grid_corners":[5,6],
"status":10
}
]
}
#include <iostream>
#include <string.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
int main(int argc, char** argv)
{
command_string = "{\"store\":[{\"grid_corners\":[0,1],\"status\":3},{\"grid_corners\":[5,6],\"status\":10}]}";
char* json = (char*)command_string.c_str();
rapidjson::Document document;
document.Parse(json);
int store_0_grid_0 = document["store"][0]["grid_corners"][0].GetInt();
int store_0_grid_1 = document["store"][0]["grid_corners"][1].GetInt();
int store_0_status = document["store"][0]["status"].GetInt();
int store_1_grid_0 = document["store"][1]["grid_corners"][0].GetInt();
int store_1_grid_1 = document["store"][1]["grid_corners"][1].GetInt();
int store_1_status = document["store"][1]["status"].GetInt();
std::cout<<store_0_grid_0<<std::endl;
std::cout<<store_0_grid_1<<std::endl;
std::cout<<store_0_status<<std::endl;
std::cout<<store_1_grid_0<<std::endl;
std::cout<<store_1_grid_1<<std::endl;
std::cout<<store_1_status<<std::endl;
return 1;
}
输出为
0
1
3
5
6
10
形式2(自由读取大小)
{
"store":[
[ 0,
[1,2,3]
],
[
[5,6,7,8,9],
2
],
[1,2],
[2,3]
]
}
请对代码自行调整
std::string command_string = "{\"store\":[[0,[1,2,3]],[[5,6,7,8,9],2],[1,2],[2,3]]}" ;
char* json = (char*)command_string.c_str();
rapidjson::Document document;
document.Parse(json);
if (document["store"].IsArray())
{
std::cout<<document["store"][0].Size()<<std::endl;
std::cout<<document["store"][0][1].Size()<<std::endl;
std::cout<<document["store"][1][0][3].GetInt()<<std::endl;
}
输出
2
3
8
补充的技巧
可以这么使用
std::string s = "store";
document[s.c_str()].IsArray()