如何解决如何使用 C++ boost 库创建带有 write_json 和 read_josn 的通用函数
我使用不同的函数,在执行每个函数时,我想创建如下所示的 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 数据。
提前致谢
解决方法
请不要将属性树用作 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;
}
}
{"message":"MSG_TestFunction1","id":"1212"}
{"message":"MSG_TestFunction1","id":"1213"}
奖金
请注意,与属性树不同,您有类型,这意味着 ID 不必是字符串:
for (auto id : {1212,1213}) {
std::cout << json::object{{"message",id}}
<< std::endl;
}
打印(Live Again):
{"message":"MSG_TestFunction1","id":1212}
{"message":"MSG_TestFunction1","id":1213}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。