rapidjson

生成

std::string slicedResultToJsonString(const cura::FffGcodeWriter::SlicedMeshInfo& slicedResult)
{
    float size_x = INT2MM(slicedResult.boundInfo.max.x - slicedResult.boundInfo.min.x);
    float size_y = INT2MM(slicedResult.boundInfo.max.y - slicedResult.boundInfo.min.y);
    float size_z = INT2MM(slicedResult.boundInfo.max.z - slicedResult.boundInfo.min.z);

    rapidjson::Document d;
    d.SetObject();
    rapidjson::Document::AllocatorType& allocator = d.GetAllocator();          // 获取分配器

    d.AddMember("size_x ", size_x, allocator);                                 // 切片后模型尺寸x
    d.AddMember("size_y ", size_y, allocator);                                 // 切片后模型尺寸y
    d.AddMember("size_z ", size_z, allocator);                                 // 切片后模型尺寸z
    d.AddMember("supplies_usage", slicedResult.totalFilamentUsed, allocator);  // 所需耗材
    d.AddMember("layers", slicedResult.totalLayers, allocator);                // 切片后模型层数
    d.AddMember("estimate", slicedResult.totalTimes, allocator);               // 预估打印时间,单位秒,
    d.AddMember("machine_name", "Anycubic", allocator);                        // 机器类型名称

    rapidjson::StringBuffer strBuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
    d.Accept(writer);

    return strBuf.GetString();
}

遍历

int loadJson(const std::string& sliceParam, Settings& settings)
{
    rapidjson::Document document;
    document.Parse(sliceParam.c_str());
    if (document.HasParseError())
    {
        return 1;
    }
	for (rapidjson::Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); itr++)
	{
		rapidjson::Value jKey;
		rapidjson::Value jValue;
		rapidjson::Document::AllocatorType allocator;
		jKey.CopyFrom(itr->name, allocator);
		jValue.CopyFrom(itr->value, allocator);

        std::string name;
        std::string value_string;

		if (jKey.IsString())
		{
            name = jKey.GetString();
		}


        if (jValue.IsString())
        {
            value_string = jValue.GetString();
        }
        else if (jValue.IsTrue())
        {
            value_string = "true";
        }
        else if (jValue.IsFalse())
        {
            value_string = "false";
        }
        else if (jValue.IsNumber())
        {
            std::ostringstream ss;
            ss << jValue.GetDouble();
            value_string = ss.str();
        }
        else
        {
            return 1;
        }
		
        settings.add(name, value_string);
	}
	return 0;
}
### RapidJSON 库简介 RapidJSON 是一种高效的 C++ JSON 解析器和生成器库,具有高性能、低内存占用的特点。它支持多种操作模式,包括 DOM(文档对象模型)、SAX(简单 API for XML 风格)以及流式解析等功能。 以下是关于如何使用 RapidJSON 的一些核心功能说明: --- ### 使用 RapidJSON 进行 JSON 数据的读取与写入 #### 1. 安装 RapidJSON 可以通过下载源码或者通过包管理工具安装 RapidJSON。如果从源码编译,则解压并将其头文件路径加入项目即可[^3]。 ```cpp #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" using namespace rapidjson; ``` 以上代码片段展示了引入 RapidJSON 所需的核心头文件。 --- #### 2. 解析 JSON 字符串 可以利用 `Document` 类来加载和解析 JSON 数据。 ```cpp // 示例 JSON 字符串 const char* jsonString = "{\"project\":\"RapidJSON\",\"stars\":100}"; // 创建 Document 对象 Document document; document.Parse(jsonString); // 访问键值对 if (document.HasMember("project") && document["project"].IsString()) { std::cout << "Project Name: " << document["project"].GetString() << std::endl; // 输出 Project Name: RapidJSON } if (document.HasMember("stars") && document["stars"].IsInt()) { std::cout << "Stars Count: " << document["stars"].GetInt() << std::endl; // 输出 Stars Count: 100 } ``` 此部分演示了如何解析简单的 JSON 字符串,并访问其中的数据成员[^4]。 --- #### 3. 构建 JSON 文档 除了解析现有 JSON 外,还可以构建新的 JSON 数据结构。 ```cpp // 创建一个新的 Document 实例 Document document; document.SetObject(); // 添加键值对 Value projectKey("project", document.GetAllocator()); Value projectName("RapidJSON", document.GetAllocator()); document.AddMember(projectKey, projectName, document.GetAllocator()); Value starsKey("stars", document.GetAllocator()); Value starCount(100); document.AddMember(starsKey, starCount, document.GetAllocator()); // 将 JSON 转换为字符串 StringBuffer buffer; Writer<StringBuffer> writer(buffer); document.Accept(writer); std::string jsonString = buffer.GetString(); std::cout << jsonString << std::endl; // 输出 {"project":"RapidJSON","stars":100} ``` 这段代码展示了一个完整的创建过程,包括设置键值对并将最终结果转换回字符串形式[^5]。 --- #### 4. 常见问题解决方法 ##### (1)处理大尺寸 JSON 文件 当遇到非常大的 JSON 文件时,建议采用 SAX 模式的解析方式以减少内存消耗。 ```cpp class MyHandler : public BaseReaderHandler<UTF8<>, MyHandler> { public: bool Null() { printf("Null\n"); return true; } bool Bool(bool b) { printf("Bool(%s)\n", b ? "true" : "false"); return true; } bool Int(int i) { printf("Int(%d)\n", i); return true; } }; FileReadStream is("/path/to/largefile.json", buffer, sizeof(buffer)); MyHandler handler; Reader reader; reader.Parse(is, handler); ``` 这里定义了一个自定义处理器类继承自 `BaseReaderHandler` 并实现了必要的回调函数[^6]。 ##### (2)编码错误 确保输入数据的字符集匹配 RapidJSON 默认使用的 UTF-8 编码标准。如果不一致可能会引发异常或不正确的行为。 --- ### 总结 RapidJSON 提供了一套强大而灵活的功能用于处理 JSON 数据,在性能上有显著优势。无论是小型嵌入式设备还是大型服务器端应用都可以找到其适用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值