21xrx.com
2024-09-20 00:09:34 Friday
登录
文章检索 我的文章 写文章
C++读写JSON文件教程
2023-07-05 00:15:00 深夜i     --     --
C++ JSON 文件读取 文件写入 教程

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于人和机器阅读和编写,并且可以被多种编程语言支持。C++是一种流行的高级编程语言,它也可以读写JSON文件。在本教程中,我们将学习如何使用C++来读写JSON文件。

首先,我们需要安装一个JSON库来帮助我们处理JSON格式。本教程将使用快速记忆(RapidJSON)库。RapidJSON是一个高效的JSON解析和生成库,它具有易于使用的API接口和高性能的功能。

安装RapidJSON库非常简单。您可以从GitHub仓库下载RapidJSON并将其复制到您的项目目录中。然后,只需包含“rapidjson/document.h”头文件即可使用库的功能。

接下来,我们将读取一个名为“example.json”的JSON文件并从中提取数据。以下是一个示例JSON文件:

  "name": "John"

现在,我们可以使用RapidJSON库来读取该文件并从中提取数据。以下是一个示例代码:

#include "rapidjson/document.h"

#include "rapidjson/filereadstream.h"

#include

int main() {

  // 从文件中读取JSON数据

  FILE* fp = fopen("example.json", "r");

  char readBuffer[65536];

  rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));

  rapidjson::Document document;

  document.ParseStream(is);

  fclose(fp);

  // 从JSON对象中提取数据

  const rapidjson::Value& name = document["name"];

  const rapidjson::Value& age = document["age"];

  const rapidjson::Value& city = document["city"];

  // 输出数据

  printf("Name: %s\n", name.GetString());

  printf("Age: %d\n", age.GetInt());

  printf("City: %s\n", city.GetString());

  return 0;

}

通过代码中的注释,您可以了解每个步骤的作用。如果您的JSON文件具有不同的结构,您可以相应地更改代码以适应新的结构。

现在,我们将了解如何将数据写入JSON文件。使用RapidJSON库,您可以轻松创建JSON对象并将其写入文件中。以下是一个示例代码:

#include "rapidjson/document.h"

#include "rapidjson/writer.h"

#include "rapidjson/stringbuffer.h"

#include

int main() {

  // 创建JSON对象

  rapidjson::Document document;

  document.SetObject();

  // 添加数据到JSON对象

  rapidjson::Value name;

  name.SetString("John");

  rapidjson::Value age;

  age.SetInt(30);

  rapidjson::Value city;

  city.SetString("New York");

  document.AddMember("name", name, document.GetAllocator());

  document.AddMember("age", age, document.GetAllocator());

  document.AddMember("city", city, document.GetAllocator());

  // 将JSON对象写入文件中

  FILE* fp = fopen("output.json", "w");

  char writeBuffer[65536];

  rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));

  rapidjson::Writer writer(os);

  document.Accept(writer);

  fclose(fp);

  return 0;

}

使用上面的代码,您可以创建一个JSON对象并为其添加数据。然后,您可以使用Writer类将JSON对象写入文件中。在此示例中,我们将JSON数据写入名为“output.json”的新文件中。

总之,C++可以轻松读取和写入JSON文件。使用RapidJSON库,您可以轻松解析和生成JSON对象,并使用API接口访问其数据。在使用时,您可以根据您的需求更改代码以适应不同的JSON文件结构。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复