【发布时间】:2021-03-28 16:53:31
【问题描述】:
我正在使用不同的函数,在执行每个函数时,我想创建 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 数据的正确方法吗? 另外请帮助我如何创建一个通用函数或一个具有读写 json 的类,以利用 TestFunction1、TestFunction2 等所有函数来创建和解析 json 数据。
提前致谢
【问题讨论】:
-
您问题顶部的代码是什么意思?它不是有效的 C++,也不是有效的 JSON。
-
一旦 TestFunction1 被执行,它会创建类似 {"message" : "MSG_TestFunction1", "id" : "1212"} 的 JSON 消息,类似 TestFunction2、TestFunction3 等。然后我们可以将此序列化的 JSON 消息发送到其他应用程序。因此,作为参考,我提到了函数(TestFunction1、TestFunction2..)中所需的 JSON 消息格式