JsonCpp 是一个 C++ 库,用于处理 JSON 数据
使用智能指针:
在 C++11 及更高版本中,可以使用智能指针(如 std::shared_ptr 和 std::unique_ptr)来自动管理内存。当智能指针超出作用域时,它们会自动释放所指向的对象。在 JsonCpp 中,可以使用 Json::Value 类的智能指针版本,如 std::shared_ptr<Json::Value>。
示例:
#include <iostream>
#include <memory>
#include <json/json.h>
int main() {
    std::string jsonString = R"(
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    )";
    std::shared_ptr<Json::Value> root = std::make_shared<Json::Value>();
    Json::CharReaderBuilder builder;
    Json::CharReader* reader = builder.newCharReader();
    std::string errors;
    if (reader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), root.get(), &errors)) {
        std::cout << "JSON parsed successfully." << std::endl;
    } else {
        std::cout << "Error parsing JSON: " << errors << std::endl;
    }
    // 使用智能指针管理 Json::Value 对象
    return 0;
}
手动管理内存:
在 C++98 和 C++03 中,需要手动管理内存。在这种情况下,需要确保在不再需要 Json::Value 对象时释放其内存。可以使用 delete 关键字来释放动态分配的内存。
示例:
#include <iostream>
#include <json/json.h>
int main() {
    std::string jsonString = R"(
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    )";
    Json::Value* root = new Json::Value();
    Json::CharReaderBuilder builder;
    Json::CharReader* reader = builder.newCharReader();
    std::string errors;
    if (reader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), root, &errors)) {
        std::cout << "JSON parsed successfully." << std::endl;
    } else {
        std::cout << "Error parsing JSON: " << errors << std::endl;
    }
    // 使用手动内存管理
    delete root;
    return 0;
}
请注意,在使用手动内存管理时,务必确保在不再需要 Json::Value 对象时释放其内存,以避免内存泄漏。在实际项目中,推荐使用智能指针来自动管理内存。