RapidJSON生成json格式文件
Json串:花括弧表示一个“容器”方括号装载数组名称和值用冒号隔开数组元素通过逗号隔开JSON示例{"name":"jack",//常规类型"age":18,"sub":["a","b"],//value是数组"elp":[ {"a":"A","b":"B"},//value是一个数组且里面每个元素又是一个json格式...
·
Json串:
花括弧表示一个“容器”
方括号装载数组
名称和值用冒号隔开
数组元素通过逗号隔开
JSON示例
{
"name":"jack", //常规类型
"age":18,
"sub":["a","b"], //value是数组
"elp":[ {"a":"A","b":"B"}, //value是一个数组且里面每个元素又是一个json格式
{"c":"C","d":"D"},
]
}
string createJson()
{
//常规操作
Document doc; //生成DOM元素
doc.SetObject();
Document::AllocatorType& allocator = doc.GetAllocator(); //生成一个分配器
//构建键值对
doc.AddMember("name","jack",allocator); //键 值 分配器
doc.AddMember("age", 18, allocator);
//"sub"
//构建数组 类型为:["1","2"]
Value array_sub(kArrayType); //创建一个数组类型对象
array_sub.PushBack("a", allocator);
array_sub.PushBack("b", allocator);
doc.AddMember("sub", array_sub, allocator); //将数组分配给sub字段
//构建数组 类型为:[{"a":"A","b","B"},{"c":"C"}] 一个数组且里面每个元素又是一个json
//"elp"
Value array_json(kArrayType); //一维数组
Value array_obj1(kObjectType); //每个数组里又是一个json格式 二级json
array_obj1.AddMember("a","A",allocator);
array_obj1.AddMember("b", "B", allocator);
array_json.PushBack(array_obj1, allocator);
Value array_obj2(kObjectType); // 二级json
array_obj2.AddMember("c", "C", allocator);
array_obj2.AddMember("d", "D", allocator);
array_json.PushBack(array_obj2, allocator);
doc.AddMember("elp", array_json, allocator);
StringBuffer s;
Writer<StringBuffer> writer(s);
doc.Accept(writer);
return std::string(s.GetString());
}
//读取json文件
void ReadJson()
{
FILE* fp = fopen("..//test.json","rb");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
Document d;
d.ParseStream(is);
fclose(fp);
printf("%s", readBuffer);
}
void writeFiles(string str) //写入json文件
{
Document docu;
string writeJson = str;
docu.Parse(writeJson.c_str());
FILE* fp = fopen("..//test.json", "wb");
char writeBuffer[65535];
rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
PrettyWriter<FileWriteStream> writer(os);
docu.Accept(writer);
fclose(fp);
}
int main()
{
string result = createJson();
writeFiles(result); //写入json文件
cout << "读取json文件:" << endl;
ReadJson();
return 0;
}
更多推荐
已为社区贡献2条内容
所有评论(0)