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 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐