腾讯rapidJson使用例子

只需要把库的头文件拿下来加入项目中使用就行,我是以二进制文件存储内容并解析:

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
#include·<rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/error/en.h>

void writeJsonToBinaryFile(const std::string& jsonString, const std::string& filename) {
    std::ofstream outFile(filename, std::ios::binary);
    if (!outFile) {
        std::cerr << "无法打开文件进行写入: " << filename << std::endl;
        return;
    }
    
    // 将 JSON 字符串写入文件
    outFile.write(jsonString.c_str(), jsonString.size());
    outFile.close();
}

std::string readBinaryFileToJsonString(const std::string& filename) {
    std::ifstream inFile(filename, std::ios::binary);
    if (!inFile) {
        std::cerr << "无法打开文件进行读取: " << filename << std::endl;
        return "";
    }

    // 读取文件内容到字符串
    std::string jsonString((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
    inFile.close();
    return jsonString;
}

int main() {

    // 创建 JSON 字符串
    rapidjson::Document document;
    document.SetObject();
    rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
    document.AddMember("name", rapidjson::Value("John", allocator), allocator);
    document.AddMember("age", 30, allocator);
    document.AddMember("isStudent", false, allocator);

    // 将 JSON 对象转换为字符串
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    document.Accept(writer);
    std::string jsonString = buffer.GetString();

    // 写入二进制文件
    writeJsonToBinaryFile(jsonString, "data.bin");
	
    // 从二进制文件读取 JSON 字符串
    std::string jsonString = readBinaryFileToJsonString("data.bin");
    if (jsonString.empty()) {
        return 1; // 读取失败
    }

    // 解析 JSON 字符串
    rapidjson::Document document2;
    if (document2.Parse(jsonString.c_str()).HasParseError()) {
        std::cerr << "JSON 解析错误: " << rapidjson::GetParseError_En(document2.GetParseError()) << std::endl;
        return 1;
    }

    // 访问 JSON 数据
    const char* name = document2["name"].GetString();
    int age = document2["age"].GetInt();
    bool isStudent = document2["isStudent"].GetBool();

    // 输出解析结果
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Is Student: " << (isStudent ? "true" : "false") << std::endl;

    return 0;
}
相关推荐
kooboo china.7 小时前
什么是JSON ?从核心语法到编辑器
javascript·编辑器·json
黑眼圈的小熊猫12 小时前
项目-- Json-Rpc框架
rpc·json·php
大千AI助手19 小时前
django中如何解析content-type=application/json的请求
django·sqlite·json
胡斌附体1 天前
接口获取到数组进行json对象转换
json·router·json.parse
python_chai2 天前
Django核心知识点全景解析
python·json
子正2 天前
C环境下更简洁的cJSON辅助函数
json
远方16093 天前
18-Oracle 23ai JSON二元性颠覆传统
数据库·oracle·json
浮生若梦l3 天前
在 Spring Boot 项目里,MYSQL中json类型字段使用
spring boot·mysql·json
远方16095 天前
16-Oracle 23 ai-JSON-Relational Duality-知识准备
数据库·oracle·json
sc写算法5 天前
基于nlohmann/json 实现 从C++对象转换成JSON数据格式
开发语言·c++·json