json文件的基本讀寫功能


1 從github上下載json源代碼,鏈接如下:https://github.com/nlohmann/json.git

2 利用json在線解析網址測試json配置文件格式是否正確,鏈接如下:https://www.json.cn/

3 將下載下來的json項目的include頭文件包含在自己的項目中的包含目錄(VS)

4 在使用json的cpp文件開始加上下面兩條語句(必須完成第三步,否則會編譯出錯)

#include <nlohmann/json.hpp>
using json = nlohmann::json;

3 讀取json文件代碼如下:

std::map<std::string, std::map<std::string, std::string>> ReadJsonFile(
const std::string &filepath) {
  std::map<std::string, std::map<std::string, std::string>> json_config;
  std::ifstream file(filepath);
  if (!file.is_open()) {
    file.clear();
    return json_config;
  }
  file.seekg(0, std::ios::end);
  int file_size = file.tellg();
  file.seekg(0, std::ios::beg);

  char *buf = new char[file_size + 1];
  memset(buf, 0, file_size + 1);
  file.read(buf, file_size);
  std::string con(buf);
  delete[]buf;
  file.close();

  try {
    json json_content;
    json_content = json::parse(con);
    json_config =
      json_content.get<std::map<std::string, std::map<std::string, std::string>>>();
  } catch (...) {
    return json_config;
  }

  return json_config;
}

 

4 寫入json文件代碼如下:

bool WriteJsonFile(const std::string& file_path,
                   std::map<std::string,  std::map<std::string, std::string>> &json_config) {
  std::ofstream file(file_path,
                     std::ios::trunc | std::ios::out | std::ios::in);

  if (!file.is_open()) {
    return false;
  }

  json js;
  for (auto p : json_config) {
    std::string objectname = p.first;
    std::map<std::string, std::string> object_config = p.second;
    json jsobject;
    for (auto k : object_config) {
      jsobject[k.first] = k.second;
    }
    js[objectname] = jsobject;
  }

  file << js;
  return true;
}

5 測試代碼如下:

void TestReadJson() {
  std::map<std::string, std::map<std::string, std::string>> json_config =
        ReadJsonFile("config.json");
  if (json_config.empty()) {
    return ;
  }
  for (auto p : json_config) {
    std::cout << p.first << std::endl;
    for (auto k : p.second) {
      std::cout << "(" << k.first << "," << k.second << ")" << std::endl;
    }
  }
}

void TestWriteJson() {
  std::map<std::string, std::map<std::string, std::string>> json_config;
  json_config["username"] = { { "username1","admin" },{ "username2","administrator" } };
  json_config["udpconfig"] = { { "ipaddress","127.0.0.1" },{ "port","1234" } };
  WriteJsonFile("config.json", json_config);
}

 

注:要使上述代碼可以直接運行,還需包含下面三個頭文件

#include <iostream>
#include <fstream>
#include <map>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM