溫馨提示×

c++ bson與json怎樣互轉

c++
小樊
158
2024-09-15 15:38:10
欄目: 編程語言

在C++中,可以使用第三方庫來實現BSON和JSON之間的轉換。這里我們將介紹如何使用bsoncxxnlohmann_json庫來實現這個功能。

首先,確保已經安裝了這兩個庫??梢酝ㄟ^vcpkg或其他包管理器進行安裝。例如,使用vcpkg安裝:

vcpkg install bsoncxx nlohmann-json

接下來,編寫一個簡單的程序來實現BSON和JSON之間的轉換:

#include<iostream>
#include<string>
#include <bsoncxx/json.hpp>
#include <nlohmann/json.hpp>

using bsoncxx::to_json;
using nlohmann::json;

int main() {
    // JSON字符串
    std::string json_str = R"({"name": "John", "age": 30, "city": "New York"})";

    // 將JSON字符串轉換為nlohmann::json對象
    json j = json::parse(json_str);

    // 將nlohmann::json對象轉換為BSON
    bsoncxx::document::value bson_doc = bsoncxx::from_json(j.dump());

    // 將BSON對象轉換回JSON字符串
    std::string json_str_converted = to_json(bson_doc.view());

    // 輸出轉換后的JSON字符串
    std::cout << "Converted JSON: "<< json_str_converted<< std::endl;

    return 0;
}

編譯并運行上述代碼,將看到輸出的轉換后的JSON字符串。

注意:在編譯時,需要鏈接bsoncxxnlohmann_json庫。例如,使用CMake:

cmake_minimum_required(VERSION 3.14)
project(bson_json_converter)

find_package(bsoncxx REQUIRED)
find_package(nlohmann_json REQUIRED)

add_executable(bson_json_converter main.cpp)
target_link_libraries(bson_json_converter bsoncxx::bsoncxx nlohmann_json::nlohmann_json)

這樣就可以實現C++中BSON和JSON之間的相互轉換了。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女