C++读写Json文件

Json库下载

Json文件是一种轻量级的数据交换格式,具体不在这介绍。对Json文件进行读写首先需要下载Json库。我使用的是rapidjson库。

rapidjson库是腾讯的实现,网址在这https://github.com/Tencent/rapidjson/

如何使用:从上面的GitHub网址git clone下来include文件夹,把它放在你的程序目录下即可

本文列举了三种情况的代码,并且还会继续更新
1. 已有json文件,并且了解其中内容,想指定更改某些内容
2. 已有json文件,并且了解其中内容,想读取它的内容
3. 没有json文件,想按照自己的想法写一个json文件

例子:
我的Json文件为example.json

{
	"A":0,
 	"B":
 	{
		"B1":10086,
		"B2":11.1
	},
	"C":[110,120,119,911],
	"D":"hello world!"
}

1. 更改Json文件

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
int main(int argc, char* argv[]){
    // json路径
    std::string json_path= "/Users/admin/Desktop/example.json";
    std::cerr << "Read Parameters" << std::endl;
    // 首先以读的方式打开json文件
    FILE* fp_read = fopen(json_path.c_str(), "r"); 
    if (fp_read == NULL)
    {
        std::cerr << "File does not exists!" << std::endl;
        return 0;
    }
    // 创建rapidjson的doc文件
    rapidjson::Document doc;
    // 读取json文件的内容
    char readBuffer[65536];
    rapidjson::FileReadStream is(fp_read, readBuffer, sizeof(readBuffer));
    doc.ParseStream(is);
    // 关闭json文件
    fclose(fp_read);

    //读取doc中你想更改的key,并更改
    rapidjson::Value& valueA = doc["A"];
    valueA.SetInt(999);
    int A = doc["A"].GetInt();
    rapidjson::Value& valueB1 = doc["B"]["B1"];
    valueB1.SetDouble(0.68001);
    rapidjson::Value& valueB2 = doc["B"]["B2"];
    valueB2.SetDouble(2.22);
    rapidjson::Value& valueC0 = doc["C"][0];
    valueC0.SetInt(11);
    rapidjson::Value& valueC1 = doc["C"][1];
    valueC1.SetInt(21);
    rapidjson::Value& valueC2 = doc["C"][2];
    valueC2.SetInt(911);
    rapidjson::Value& valueC3 = doc["C"][3];
    valueC3.SetInt(119);
    rapidjson::Value& valueD = doc["D"];
    valueD.SetString("world hello!");
  
    // 再以写的方式打开json文件
    FILE* fp_write = fopen(json_path.c_str(), "w"); 
    // 创建rapidjson的writer
    char writebuffer[65536];
    rapidjson::FileWriteStream os(fp_write, writebuffer, sizeof(writebuffer));
    rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os);
    // 将doc的更改写进json文件
    doc.Accept(writer);
    // 关闭json文件
    fclose(fp_write);
    
    return 0;
}

会发现json文件变为了

{
    "A": 999,
    "B": {
        "B1": 0.68001,
        "B2": 2.22
    },
    "C": [
        11,
        21,
        911,
        119
    ],
    "D": "world hello!"
}

2. 读取Json文件

读取json文件的代码

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"

int main(int argc, char* argv[]){
    std::string json_path= "/Users/admin/Desktop/example.json";
    std::cerr << "Read Parameters" << std::endl;
    FILE* fp = fopen(json_path.c_str(), "r"); 
    if (fp == NULL)
    {
        std::cerr << "File does not exists!" << std::endl;
        return 0;
    }
    char readBuffer[65536];
    rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
    rapidjson::Document doc;
    doc.ParseStream(is);
    fclose(fp);

    int A = doc["A"].GetInt();
    double B1 = doc["B"]["B1"].GetDouble();
    double B2 = doc["B"]["B2"].GetDouble();
    double C[4];
    C[0] = doc["C"][0].GetDouble();
    C[1] = doc["C"][1].GetDouble();
    C[2] = doc["C"][2].GetDouble();
    C[3] = doc["C"][3].GetDouble();
    std::string D = doc["D"].GetString();
	
    std::cout<<A<<std::endl;
    std::cout<<B1<<std::endl;
    std::cout<<B2<<std::endl;
    std::cout<<C[0]<<std::endl;
    std::cout<<C[1]<<std::endl;
    std::cout<<C[2]<<std::endl;
    std::cout<<C[3]<<std::endl;
    std::cout<<D<<std::endl;
    
    return 0;
}

输出结果为

Read Parameters
0
10086
11.1
110
120
119
911
hello world!

3. 向Json文件写入

向指定json文件写入数据的代码

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
int main(int argc, char* argv[]){
    std::string json_path= "/Users/admin/Desktop/example.json";
    std::cerr << "Write Parameters" << std::endl;
    
    rapidjson::Document doc;
    doc.SetObject();
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();

    rapidjson::Value A(rapidjson::kArrayType);
    int a = 0;
    doc.AddMember("A", a, allocator);

    rapidjson::Value B(rapidjson::kArrayType);
    B.SetObject();
    rapidjson::Value B1(rapidjson::kArrayType);
    double s_b1 = 10086;
    B.AddMember("B1", s_b1, allocator);
    rapidjson::Value B2(rapidjson::kArrayType);
    double s_b2 = 11.1;
    B.AddMember("B2", s_b2, allocator);
    doc.AddMember("B", B, allocator);

    rapidjson::Value C(rapidjson::kArrayType);
    C.PushBack(110, allocator);
    C.PushBack(120, allocator);
    C.PushBack(119, allocator);
    C.PushBack(911, allocator);
    doc.AddMember("C", C, allocator);

    rapidjson::Value D;
    D.SetString("hello world!",allocator);
    doc.AddMember("D", D, allocator);

    FILE* fp = fopen(json_path.c_str(), "w"); 
    char writeBuffer[65536];
    rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os);
    doc.Accept(writer);
    fclose(fp);

    return 0;
}

写入结果

{
    "A": 0,
    "B": {
        "B1": 10086.0,
        "B2": 11.1
    },
    "C": [
        110,
        120,
        119,
        911
    ],
    "D": "hello world!"
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值