C++读写文件之在Json数组追加元素(二十八)
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
1.代码示例
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cassert>
#include "json/json.h"
#include <vector>
#include <unistd.h>
using namespace std;
struct Person{
string name;
string ID;
int age;
}pinfo;
void parseFile(string &path, Json::Value &root, struct Person info){
std::ifstream ifs;
Json::Reader reader;
ifs.open(path);
if(reader.parse(ifs, root,false) != true){
cout <<"line: " << __LINE__ << " parse error..." << " root.size = " << root.size() << endl;
ifs.close();
}
if(ifs.is_open())
ifs.close();
}
void writeJson(string &path, struct Person info)
{
std::ofstream fout;
Json::Value root;
Json::Reader reader;
std::ifstream ifs;
parseFile(path, root, info);
Json::Value array = root["array"];
Json::Value item;
item["name"] = info.name;
item["ID"] = info.ID;
array.append(item);
root["array"] = array;
fout.open(path);
fout << root.toStyledString();
fout.close();
}
void readJson(string &path, Json::Value &root)
{
std::ifstream ifs;
Json::Reader reader;
//Json::Value root;
ifs.open(path);
if (!reader.parse(ifs, root,false)){
ifs.close();
return;
}
ifs.close();
}
int main(){
string path = "123.txt";
Json::Value root;
pinfo.name = "小黑";
pinfo.ID = "0.8 0.7 0.6 0.5 0.4 0.3";
writeJson(path, pinfo);
readJson(path, root);
Json::Value arrayObj = root["array"];
cout << "arrayObj.size = " << arrayObj.size() << endl;
for(unsigned int i = 0; i < arrayObj.size(); i++){
cout << "name = " << arrayObj[i]["name"].asString() << endl;
cout << "ID = " << arrayObj[i]["ID"].asString() << endl;
}
}
jsoncpp库:https://gitee.com/Tocy/SampleCode/tree/master/JsonCppTutorial
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献15条内容
所有评论(0)