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

C++读写文件之在Json数组追加元素

2018-02-09 12:03 519 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐