官网:http://rapidjson.org/zh-cn/index.html
安装
RapidJSON 是只有头文件的 C++ 库。只需把 include/rapidjson 目录复制至系统或项目的 include 目录中。一些网上例子
NO.1
[
{
"bank_name" : "BOA",
"chain_num":123,
"servers":[
{
"ip" : "127.0.0.1",
"port" : 1111
},
{
"ip" : "127.0.0.1",
"port" : 2222
}
]
},
{
"bank_name" : "CITIBANK",
"chain_num":789,
"servers":[
{
"ip" : "127.0.0.1",
"port" : 3333
},
{
"ip" : "127.0.0.1",
"port" : 4444
}
]
}
]
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h"
#include <cstdio>
#include <iostream>
#include <string>
using namespace rapidjson;
using namespace std;
int main()
{
FILE *fp = fopen("t2.json", "r");
FileStream is(fp);
Document bank;
bank.ParseStream<0>(is);
if (bank.HasParseError())
{
printf("GetParseError %s\n", bank.GetParseError());
}
for (unsigned int i = 0; i < bank.Size(); ++i)
{
const Value & cur_bank = bank[i];
cout <<"BANK # "<< i+1 <<endl;
cout <<"bank_name: "<<cur_bank["bank_name"].GetString() << endl;
cout <<"chain_num: " <<cur_bank["chain_num"].GetInt() << endl;
Value & server_array = bank[i]["servers"];
for (unsigned int j = 0; j < server_array.Size(); ++j)
{
cout <<"IP: "<<server_array[j]["ip"].GetString() << " ";
cout <<"PORT: "<<server_array[j]["port"].GetInt() << " ";
cout <<endl;
}
cout <<endl;
}
return 0;
}
NO.2 解析嵌套数组json
{
"Info": [
{
"lots": 10,
"order_algorithm": "01",
"buy_close": 9000,
"spread_shift": 0,
"position_b_sell": 0,
"position_a_buy_today": 0,
"position_a_buy_yesterday": 0,
"sell_open": -9000,
"list_instrument_id": [
"rb1705",
"rb1701"
],
"position_b_buy_today": 0,
"buy_open": -9000,
"position_a_sell_yesterday": 0,
"strategy_id": "02",
"position_b_buy": 0,
"a_wait_price_tick": 1,
"trade_model": "boll_reversion",
"b_wait_price_tick": 0,
"sell_close": 9000,
"only_close": 0,
"order_action_limit": 400,
"is_active": 1,
"lots_batch": 1,
"position_a_sell": 0,
"position_b_buy_yesterday": 0,
"user_id": "063802",
"position_a_buy": 0,
"trader_id": "1601",
"position_a_sell_today": 0,
"stop_loss": 0,
"position_b_sell_today": 0,
"position_b_sell_yesterday": 0,
"on_off": 0
},
{
"lots": 10,
"order_algorithm": "01",
"buy_close": 9000,
"spread_shift": 0,
"position_b_sell": 0,
"position_a_buy_today": 0,
"position_a_buy_yesterday": 0,
"sell_open": -9000,
"list_instrument_id": [
"ni1705",
"ni1701"
],
"position_b_buy_today": 0,
"buy_open": -9000,
"position_a_sell_yesterday": 0,
"strategy_id": "01",
"position_b_buy": 0,
"a_wait_price_tick": 1,
"trade_model": "boll_reversion",
"b_wait_price_tick": 0,
"sell_close": 9000,
"only_close": 0,
"order_action_limit": 400,
"is_active": 1,
"lots_batch": 1,
"position_a_sell": 0,
"position_b_buy_yesterday": 0,
"user_id": "063802",
"position_a_buy": 0,
"trader_id": "1601",
"position_a_sell_today": 0,
"stop_loss": 0,
"position_b_sell_today": 0,
"position_b_sell_yesterday": 0,
"on_off": 0
}
],
"MsgSendFlag": 0,
"MsgErrorReason": "ID or password error",
"MsgRef": 1,
"MsgType": 3,
"MsgResult": 0
}
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. Parse a JSON string into DOM.
const char* json ="{\"Info\":[{\"lots\":10,\"order_algorithm\":\"01\",\"buy_close\":9000,\"spread_shift\":0,\"position_b_sell\":0,\"position_a_buy_today\":0,\"position_a_buy_yesterday\":0,\"sell_open\":-9000,\"list_instrument_id\":[\"rb1705\",\"rb1701\"],\"position_b_buy_today\":0,\"buy_open\":-9000,\"position_a_sell_yesterday\":0,\"strategy_id\":\"02\",\"position_b_buy\":0,\"a_wait_price_tick\":1,\"trade_model\":\"boll_reversion\",\"b_wait_price_tick\":0,\"sell_close\":9000,\"only_close\":0,\"order_action_limit\":400,\"is_active\":1,\"lots_batch\":1,\"position_a_sell\":0,\"position_b_buy_yesterday\":0,\"user_id\":\"063802\",\"position_a_buy\":0,\"trader_id\":\"1601\",\"position_a_sell_today\":0,\"stop_loss\":0,\"position_b_sell_today\":0,\"position_b_sell_yesterday\":0,\"on_off\":0},{\"lots\":20,\"order_algorithm\":\"02\",\"buy_close\":9000,\"spread_shift\":0,\"position_b_sell\":0,\"position_a_buy_today\":0,\"position_a_buy_yesterday\":0,\"sell_open\":-9000,\"list_instrument_id\":[\"ni1705\",\"ni1701\"],\"position_b_buy_today\":0,\"buy_open\":-9000,\"position_a_sell_yesterday\":0,\"strategy_id\":\"01\",\"position_b_buy\":0,\"a_wait_price_tick\":1,\"trade_model\":\"boll_reversion\",\"b_wait_price_tick\":0,\"sell_close\":9000,\"only_close\":0,\"order_action_limit\":400,\"is_active\":1,\"lots_batch\":1,\"position_a_sell\":0,\"position_b_buy_yesterday\":0,\"user_id\":\"063802\",\"position_a_buy\":0,\"trader_id\":\"1601\",\"position_a_sell_today\":0,\"stop_loss\":0,\"position_b_sell_today\":0,\"position_b_sell_yesterday\":0,\"on_off\":0}],\"MsgSendFlag\":0,\"MsgErrorReason\":\"IDorpassworderror\",\"MsgRef\":1,\"MsgType\":3,\"MsgResult\":0}";
//std::cout << json << std::endl;
//std::cout << "\n" << std::endl;
std::cout << "|==================|" << std::endl;
std::cout << "||rapidjson output||" << std::endl;
std::cout << "|==================|" << std::endl;
Document doc;
doc.Parse(json);
// 2. Modify it by DOM.
Value& s = doc["MsgSendFlag"];
s.SetInt(s.GetInt() + 1);
Value& infoArray = doc["Info"];
if (infoArray.IsArray()) {
for (int i = 0; i < infoArray.Size(); i++) {
const Value& object = infoArray[i];
int lots = object["lots"].GetInt();
std::string order_algorithm = object["order_algorithm"].GetString();
std::cout << "int lots = " << lots << std::endl;
std::cout << "string order_algorithm = " << order_algorithm << std::endl;
const Value& info_object = object["list_instrument_id"];
if (info_object.IsArray()) {
for (int j = 0; j < info_object.Size(); j++) {
std::string instrument = info_object[j].GetString();
std::cout << "instrument[" << j << "] = " << instrument << std::endl;
}
}
}
}
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}
NO.3 创建嵌套数组Json文本
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. Parse a JSON string into DOM.
const char* json ="{\"Info\":[{\"lots\":10,\"order_algorithm\":\"01\",\"buy_close\":9000,\"spread_shift\":0,\"position_b_sell\":0,\"position_a_buy_today\":0,\"position_a_buy_yesterday\":0,\"sell_open\":-9000,\"list_instrument_id\":[\"rb1705\",\"rb1701\"],\"position_b_buy_today\":0,\"buy_open\":-9000,\"position_a_sell_yesterday\":0,\"strategy_id\":\"02\",\"position_b_buy\":0,\"a_wait_price_tick\":1,\"trade_model\":\"boll_reversion\",\"b_wait_price_tick\":0,\"sell_close\":9000,\"only_close\":0,\"order_action_limit\":400,\"is_active\":1,\"lots_batch\":1,\"position_a_sell\":0,\"position_b_buy_yesterday\":0,\"user_id\":\"063802\",\"position_a_buy\":0,\"trader_id\":\"1601\",\"position_a_sell_today\":0,\"stop_loss\":0,\"position_b_sell_today\":0,\"position_b_sell_yesterday\":0,\"on_off\":0},{\"lots\":20,\"order_algorithm\":\"02\",\"buy_close\":9000,\"spread_shift\":0,\"position_b_sell\":0,\"position_a_buy_today\":0,\"position_a_buy_yesterday\":0,\"sell_open\":-9000,\"list_instrument_id\":[\"ni1705\",\"ni1701\"],\"position_b_buy_today\":0,\"buy_open\":-9000,\"position_a_sell_yesterday\":0,\"strategy_id\":\"01\",\"position_b_buy\":0,\"a_wait_price_tick\":1,\"trade_model\":\"boll_reversion\",\"b_wait_price_tick\":0,\"sell_close\":9000,\"only_close\":0,\"order_action_limit\":400,\"is_active\":1,\"lots_batch\":1,\"position_a_sell\":0,\"position_b_buy_yesterday\":0,\"user_id\":\"063802\",\"position_a_buy\":0,\"trader_id\":\"1601\",\"position_a_sell_today\":0,\"stop_loss\":0,\"position_b_sell_today\":0,\"position_b_sell_yesterday\":0,\"on_off\":0}],\"MsgSendFlag\":0,\"MsgErrorReason\":\"IDorpassworderror\",\"MsgRef\":1,\"MsgType\":3,\"MsgResult\":0}";
//std::cout << json << std::endl;
//std::cout << "\n" << std::endl;
std::cout << "|==================|" << std::endl;
std::cout << "||rapidjson output||" << std::endl;
std::cout << "|==================|" << std::endl;
Document doc;
doc.SetObject();
rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
doc.AddMember("MsgSendFlag", 1, allocator);
doc.AddMember("MsgErrorReason", "IDorpassworderror", allocator);
doc.AddMember("MsgRef", 1, allocator);
rapidjson::Value info_array(rapidjson::kArrayType);
for (int i = 0; i < 2; i++) {
rapidjson::Value info_object(rapidjson::kObjectType);
info_object.SetObject();
info_object.AddMember("lots", 10 + i, allocator);
info_object.AddMember("order_algorithm", "01", allocator);
rapidjson::Value instrument_array(rapidjson::kArrayType);
for (int j = 0; j < 2; j++) {
rapidjson::Value instrument_object(rapidjson::kObjectType);
instrument_object.SetObject();
instrument_object.SetString("cu1701");
instrument_array.PushBack(instrument_object, allocator);
}
info_object.AddMember("list_instrument_id", instrument_array, allocator);
info_array.PushBack(info_object, allocator);
}
doc.AddMember("Info", info_array, allocator);
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}
NO.4
{"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}]}
#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;
*/
}
NO.5
#include <iostream>
#include <string>
#include <fstream>
//包含rapidjson必要头文件,rapidjson文件夹拷贝到工程目录,或者设置include路径,或者加入到工程树
#include "rapidjson/document.h"
#include "rapidjson/filestream.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace std;
using namespace rapidjson; //引入rapidjson命名空间
//写json文件
void json_write()
{
Document doc;
doc.SetObject();
Document::AllocatorType &allocator=doc.GetAllocator(); //获取分配器
//1.添加字符串对象
doc.AddMember("author","tashaxing",allocator);
//2.添加数组对象
Value array1(kArrayType);
for(int i=0;i<3;i++)
{
Value int_object(kObjectType);
int_object.SetInt(i);
array1.PushBack(int_object,allocator);
}
doc.AddMember("number",array1,allocator);
//3.添加复合对象
Value object(kObjectType);
object.AddMember("language1","C++",allocator);
object.AddMember("language2","java",allocator);
doc.AddMember("language",object,allocator);
//4.添加对象数组和复合对象的组合
Value array2(kArrayType);
Value object1(kObjectType);
object1.AddMember("hobby","drawing",allocator);
array2.PushBack(object1,allocator);
Value object2(kObjectType);
object2.AddMember("height",1.71,allocator);
array2.PushBack(object2,allocator);
doc.AddMember("information",array2,allocator);
StringBuffer buffer;
PrettyWriter<StringBuffer> pretty_writer(buffer); //PrettyWriter是格式化的json,如果是Writer则是换行空格压缩后的json
doc.Accept(pretty_writer);
//打印到屏幕
cout<<"the json output:"<<endl;
cout<<buffer.GetString()<<endl;
//输出到文件
ofstream fout;
fout.open("test"); //可以使绝对和相对路径,用\\隔开目录,test, test.json, test.txt 都行,不局限于文件格式后缀,只要是文本文档
fout<<buffer.GetString();
fout.close();
}
//读json文件
void json_read()
{
cout<<"the json read:"<<endl;
ifstream fin;
fin.open("test");
string str;
string str_in="";
while(getline(fin,str)) //一行一行地读到字符串str_in中
{
str_in=str_in+str+'\n';
}
//解析并打印出来
Document document;
document.Parse<0>(str_in.c_str());
Value &node1=document["author"];
cout<<"author: "<<node1.GetString()<<endl;
Value &node2=document["number"];
cout<<"number: "<<endl;
if(node2.IsArray())
{
for(int i=0;i<node2.Size();i++)
cout<<'\t'<<node2[i].GetInt()<<endl;
}
Value &node3=document["language"];
cout<<"language: "<<endl;
Value &tmp=node3["language1"];
cout<<'\t'<<"language1: "<<tmp.GetString()<<endl;
tmp=node3["language2"];
cout<<'\t'<<"language2: "<<tmp.GetString()<<endl;
Value &node4=document["information"];
cout<<"information: "<<endl;
if(node4.IsArray())
{
int i=0;
Value &data=node4[i]; //注意,此处下表索引只能用变量,不能用常量,例如node[0]编译错误
cout<<'\t'<<"hobby: "<<data["hobby"].GetString()<<endl;
i=1;
data=node4[i];
cout<<'\t'<<"height: "<<data["height"].GetDouble()<<endl;
}
}
int main(int argc,char **argv)
{
//写、读 测试
json_write();
json_read();
return 0;
}
自己实现的读写
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <tuple>
#include <time.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
//#include "rapidjson/filestream.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
int main_loadtest()
{
FILE *fp = fopen("test.json", "r");
//FileStream is(fp);
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
/*Document d;
d.ParseStream(is);
fclose(fp);*/
Document bank;
bank.ParseStream<0>(is);
if (bank.HasParseError())
{
printf("GetParseError %s\n", bank.GetParseError());
}
for (unsigned int i = 0; i < bank.Size(); ++i)
{
const Value & cur_bank = bank[i];
cout << "BANK # " << i + 1 << endl;
cout << "bank_name: " << cur_bank["bank_name"].GetString() << endl;
cout << "chain_num: " << cur_bank["chain_num"].GetInt() << endl;
Value & server_array = bank[i]["servers"];
for (unsigned int j = 0; j < server_array.Size(); ++j)
{
cout << "IP: " << server_array[j]["ip"].GetString() << " ";
cout << "PORT: " << server_array[j]["port"].GetInt() << " ";
cout << endl;
}
cout << endl;
}
fclose(fp);
system("pause");
return 0;
}
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;
}
//void load_rank_data(const string filename, vector<vector<string>> &pair_picname_label_vector, vector<string> &picnames_vector
void load_rank_data(const string filename, vector<vector<string>> *p, vector<string> *picnames_vector)
{
//vector<string> tmp_picname_label_vector;
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());
if (d.HasMember("pic_name") && d["pic_name"].IsArray()) {
Value & pic_name = d["pic_name"];
string tmp_pic_name;
//int temp_ima_id, temp_ques_id;
if (pic_name.IsArray())
{
for (size_t i = 0; i < pic_name.Size(); ++i)
{
tmp_pic_name = pic_name[i].GetString();
(*picnames_vector).push_back(tmp_pic_name);
cout << "instrument[" << i << "] = " << tmp_pic_name << std::endl;
}
}
//cout << "-----------------***********************-----------------" << endl;
//for (int i = 0; i < picnames_vector.size(); i++)
//{
// cout << picnames_vector[i] << endl;
//}
//cout << "-----------------***********************-----------------" << endl;
//for (vector<string>::iterator iter = picnames_vector.begin(); iter != picnames_vector.end(); iter++)
//{
// cout << *iter << endl;
// 下面两种方法都行
// (*iter).empty() 如果不含有任何元素,返回真;否则返回假。
// //cout << (*iter).empty() << endl;
// //cout << iter->empty() << endl;
//}
}
if (d.HasMember("pair_label_name") && d["pair_label_name"].IsArray()) {
Value& pair_label_name = d["pair_label_name"];
string tmp_sub;
for (int i = 0; i < pair_label_name.Size(); i++) {
const Value& pair_label = pair_label_name[i];
vector<string> *pt = new vector<string>;
if (pair_label.IsArray()) {
for (int j = 0; j < pair_label.Size(); j++) {
tmp_sub = pair_label[j].GetString();
//tmp_picname_label_vector.push_back(tmp_sub);
(*pt).push_back(tmp_sub);
cout << tmp_sub << " ";
}
}
//pair_picname_label_vector.push_back(tmp_picname_label_vector);
//(*p).push_back(tmp_picname_label_vector);
(*p).push_back(*pt);
delete pt;
cout << endl;
cout << "-----------------************[" << i << "]***********-----------------" << endl;
}
显示嵌套数组
//cout << "-----------------***********************-----------------" << endl;
//for (int i = 0; i < (*p).size(); i++)
//{
// for (int j = 0; j < (*p)[i].size(); j++)
// {
// cout << (*p)[i][j] << endl;
// }
//}
//cout << "-----------------***********************-----------------" << endl;
//for (vector<vector<string>>::iterator iter = (*p).begin(); iter != (*p).end(); iter++)
//{
// for (vector<string>::iterator sub_iter = (*iter).begin(); sub_iter != (*iter).end(); sub_iter++)
// {
// cout << *sub_iter << endl;
// 下面两种方法都行
// (*sub_iter).empty() 如果不含有任何元素,返回真;否则返回假。
// //cout << (*sub_iter).empty() << endl;
// //cout << sub_iter->empty() << endl;
// }
//}
}
}
int main()
{
double start, stop, durationTime;
start = clock();
//string filename = "test_2.json";
string filename = "rank_pair_data.json";
vector<tuple<string, int, int>> result;
vector<vector<string>> pair_picname_label_vector;
//vector<string> picnames_vector;
//json_analysis(filename, result);
vector<string> *picnames_vector = new vector<string>;
vector<vector<string>> *p = new vector<vector<string>>;
load_rank_data(filename, p, picnames_vector);
delete p;
stop = clock();
durationTime = ((double)(stop - start)) / CLK_TCK;
cout << "程序耗时:" << durationTime << " s" << endl;
system("pause");
return 0;
}