1、json文件
{
"Address" : "北京",
"Color" : [ 0.80000000000000004, 1.0, 0.5 ],
"Date" : 1998,
"Info" :
{
"Class" : "三年级",
"Part" : "西城区",
"School" : "北京一中"
},
"Students" :
[
{
"Id" : 1,
"ontime" : true,
"sex" : "男",
"time" : "2021-01-16"
},
{
"Id" : 2,
"ontime" : true,
"sex" : "男",
"time" : "2021-01-16"
}
],
"baseType" : "学校"
}
2、读写json文件
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
#include "json/json.h"
void CreateJsonFile()
{
std::string strFilePath = "test.json";
Json::Value root;
root["Address"] = "北京";
root["baseType"] = "学校";
root["Date"] = 1998;
root["Info"]["School"] = "北京一中";
root["Info"]["Part"] = "西城区";
root["Info"]["Class"] = "三年级";
root["Color"].append(0.8);
root["Color"].append(1.0);
root["Color"].append(0.5);
for (int i = 0; i < 2; i++)
{
root["Students"][i]["Id"] = i+1;
root["Students"][i]["sex"] = "男";
root["Students"][i]["ontime"] = true;
root["Students"][i]["time"] = "2021-01-16";
}
Json::StyledStreamWriter streamWriter;
ofstream outFile(strFilePath);
streamWriter.write(outFile, root);
outFile.close();
std::cout << "json文件生成成功!" << endl;
}
void ReadJsonFile()
{
std::string strFilePath = "test.json";
Json::Reader json_reader;
Json::Value rootValue;
ifstream infile(strFilePath.c_str(), ios::binary);
if (!infile.is_open())
{
cout << "Open config json file failed!" << endl;
return;
}
if (json_reader.parse(infile, rootValue))
{
string sAddress = rootValue["Address"].asString();
cout << "Address = " << sAddress << endl;
int nDate = rootValue["Date"].asInt();
cout << "Date = " << nDate << endl;
cout << endl;
string sSchool = rootValue["Info"]["School"].asString();
cout << "School = " << sSchool << endl;
cout << endl;
Json::Value colorResult = rootValue["Color"];
if (colorResult.isArray())
{
for (unsigned int i = 0; i < colorResult.size(); i++)
{
double dColor = colorResult[i].asDouble();
cout << "Color = " << dColor << endl;
}
}
cout << endl;
Json::Value studentResult = rootValue["Students"];
if (studentResult.isArray())
{
for (unsigned int i = 0; i < studentResult.size(); i++)
{
int nId = studentResult[i]["Id"].asInt();
cout << "Id = " << nId << endl;
string sTime = studentResult[i]["time"].asString();
cout << "Time = " << sTime << endl;
}
}
}
else
{
cout << "Can not parse Json file!";
}
infile.close();
}
int main()
{
ReadJsonFile();
return 0;
}