主要代码如下
#include <iostream>
using namespace std;
#include <string>
#include "json/json.h"
#pragma comment(lib,"json_vc71_libmt.lib")
#include "fstream"
#include <assert.h>
int ReadFromFile(string fileName)
{
ifstream fin;
fin.open(fileName);
assert(fin.is_open());
Json::Reader reader;
Json::Value root;
if (!reader.parse(fin, root, false))
{
return -1;
}
// 获取数组中的数据
cout << "array data:" << endl;
int arraySize = root["array"]["map"].size();
for (int i = 0; i < arraySize; i++)
{
Json::Value valKeyValue = root["array"]["map"][i]["arrayMap"];
string tempKeyValue = valKeyValue.asString();
cout << "array map arrayMap:" << tempKeyValue << endl;
}
cout << endl;
cout << "my age is:" << root["array"]["age"] << endl;
int arraySize2 = root["array"]["array1"].size();
for (int i = 0; i < arraySize2; i++)
{
Json::Value valKeyValue = root["array"]["array1"][i]["key"];
int tempKeyValue = valKeyValue.asInt();
cout << "tempKeyValue:" << tempKeyValue << endl;
}
}
int WriteToFile(string fileName)
{
ofstream fout;
fout.open(fileName);
assert(fout.is_open());
Json::Value root;
Json::Value arrayobj;
Json::Value item;
Json::Value arrayMap;
for (int i = 0; i < 10;i++)
{
item["arrayMap"] = "zengraoli";
arrayMap.append(item);
}
root["array"]["map"] = arrayMap;
root["array"]["age"] = 18;
Json::Value item2;
for (int i = 0; i < 10;i++)
{
item2["key"] = i;
arrayobj.append(item2);
}
root["array"]["array1"] = arrayobj;
std::string out = root.toStyledString();
fout << root.toStyledString() << endl;
return 0;
}
int main()
{
WriteToFile("video.json");
ReadFromFile("video.json");
return 0;
}