如何使用 C++ boost 库创建具有 write_json 和 read_josn 的通用函数

How to create a generic function with write_json and read_josn using C++ boost library

我正在使用不同的功能,在执行每个功能时,我想创建 Json 消息进行通信,如下所示:

TestFunction1(string id)
{
    "message" : "MSG_TestFunction1",
        "id" : "1212"
}

TestFunction2(string id)
{
    "message" : "MSG_TestFunction2",
        "id" : "1213"
}

在这种情况下,我认为不需要维护 .JSON 文件,因为我们可以在函数本身中创建 json 消息(如 TestFunction1 和 TestFunction2 等).

考虑到所有这些,我使用带有 write_json 和 read_json 的 BOOST 库创建了以下示例。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include<string>

using namespace boost::property_tree;
using namespace std;

bool TestFunction1(std::string f_id)
{
    ptree strTree;
    ptree subject_info;
    ptree array1;
    array1.put("message", "MSG_TestFunction1");
    array1.put("id", f_id);
    
    subject_info.push_back(make_pair("", array1));

    stringstream s;
    write_json(s, array1);
    string outstr = s.str();

    stringstream stream(outstr);
    ptree strreadTree;
    try {
        read_json(stream, strreadTree);
    }
    catch (ptree_error& e) {
        return false;
    }
    return true;
}

int main()
{
    TestFunction1("1212");
    system("pause");

    return 0;
}

这是创建和解析 json 数据的正确方法吗? 另外请帮助我如何创建一个通用函数或一个 class 与写入和读取 json 以利用所有函数,如 TestFunction1、TestFunction2 等来创建和解析 json 数据。

提前致谢

请不要将 属性 树用作 JSON 库。

Boost 1.75.0 添加了一个 JSON 库!

正如另一位评论者所说,您的具体需求不是很清楚,所以让我简单介绍几个类似的用例:

#include <boost/json.hpp>
#include <boost/json/src.hpp> // for compiler explorer
#include <string>
#include <iostream>

namespace json = boost::json;

json::value TestFunction(std::string const id) {
    return json::object{
        {"message", "MSG_TestFunction1"},
        {"id", id}
    };
}

int main() {
    for (auto id : {"1212", "1213"}) {
        json::error_code ec;
        auto jsonString = serialize(TestFunction(id));
        auto roundtrip = json::parse(jsonString);

        std::cout << roundtrip << std::endl;
    }
}

打印 Live On Compiler Explorer

{"message":"MSG_TestFunction1","id":"1212"}
{"message":"MSG_TestFunction1","id":"1213"}

奖金

请注意,与 属性 树不同,您有类型,这意味着 ID 不必是字符串:

for (auto id : {1212, 1213}) {
    std::cout << json::object{{"message", "MSG_TestFunction1"}, {"id", id}}
              << std::endl;
}

打印(Live Again):

{"message":"MSG_TestFunction1","id":1212}
{"message":"MSG_TestFunction1","id":1213}