您的位置:首页 > 编程语言 > C语言/C++

rapidjson初探——使用C++解析json

2016-05-01 15:43 471 查看
刚开始想用jsoncpp的,发现这东西相当不友好,VS2013就是编译不了,于是就弃坑了

发现rapidjson超级好用,只需要包含头文件,也就是可以跨平台

虽然写很复杂的功能的时候可能需要自己封装一些接口,但是写简单的json解析完全够用了

如果是有一个文件,里面有json格式的字符串

那么只需要用文件流把这个字符串送到一个string里

然后创建一个Document对象

再把string转成const char *类型以后送到rapidjson自带的函数Parse里处理就好了

我当时遇到的是这样的json字符串:

{"info": {"description": "This is v1.0 of the VQA dataset.", "url": "http://visualqa.org", "version": "1.0", "year": 2015, "contributor": "VQA Team", "date_created": "2015-10-02 19:35:04"}, "task_type": "Open-Ended", "data_type": "mscoco", "license": {"url": "http://creativecommons.org/licenses/by/4.0/", "name": "Creative Commons Attribution 4.0 International License"}, "data_subtype": "val2014", "questions": [{"question": "What is the table made of?", "image_id": 350623, "question_id": 3506232}, {"question": "Is the food napping on the table?", "image_id": 350623, "question_id": 3506230}, {"question": "What has been upcycled to make lights?", "image_id": 350623, "question_id": 3506231}, {"question": "Is there water in the water bottle?", "image_id": 552610, "question_id": 5526102}]}


可以发现"questions"这个标签下其实是一个数组

所以就先利用

Value & ques = d["questions"];

把questions标签下的内容都放到一个Value对象里面

可以利用rapidjson自带的ques.IsArray()来检测是不是数组

然后再遍历这个数组

利用v.HasMember("question")来检测是否带有这个标签,如果带有这个标签的话再利用v["question"].IsString()来检测是否是这个类型

都符合的话就用temp_ques = v["question"].GetString();把它抓取出来

另外的两个也同理

总的代码如下:

#include <cstdio>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <tuple>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/stringbuffer.h"

using namespace std;
using namespace rapidjson;

void json_analysis(const string filename, vector<tuple<string, int, int>> &result)
{
ifstream json_file;
json_file.open(filename.c_str());
string json;
if (!json_file.is_open())
{
cout << "Error opening file" << endl;
exit(1);
}
getline(json_file, json);
Document d;
d.Parse<0>(json.c_str());
Value & ques = d["questions"];
string temp_ques;
int temp_ima_id, temp_ques_id;
if (ques.IsArray())
{
for (size_t i = 0; i < ques.Size(); ++i)
{
Value & v = ques[i];
assert(v.IsObject());
if (v.HasMember("question") && v["question"].IsString()) {
temp_ques = v["question"].GetString();
}
if (v.HasMember("image_id") && v["image_id"].IsInt()) {
temp_ima_id = v["image_id"].GetInt();
}
if (v.HasMember("question_id") && v["question_id"].IsInt()) {
temp_ques_id = v["question_id"].GetInt();
}
auto temp = make_tuple(temp_ques, temp_ima_id, temp_ques_id);
result.push_back(temp);
}
}
/*
for (size_t i = 0; i < result.size(); i++){
cout << get<0>(result[i]) << endl;
cout << get<1>(result[i]) << endl;
cout << get<2>(result[i]) << endl;
}
return 0;
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: