目录
一、编译、安装poco
参考:https://blog.csdn.net/fengbohello/article/details/118335212
二、使用poco创建JSON
#include <iostream>
#include <Poco/JSON/Parser.h>
int main(int argc, char **argv)
{
Poco::JSON::Object json;
json.set(std::string("key"), std::string("value"));
Poco::JSON::Object subjson;
subjson.set(std::string("subkey"), std::string("subvalue"));
json.set(std::string("sub"), subjson);
std::ostringstream oss;
json.stringify(oss);
std::cout << oss.str() << std::endl;
return 0;
}
Object::stringify() 函数将 Poco::JSON::Object 转为 string 形式,函数声明和定义如下:
poco/JSON/include/Poco/JSON/Object.h:
namespace Poco {
namespace JSON {
class JSON_API Object
{
public:
void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const;
/// Prints the object to out stream.
///
/// When indent is 0, the object will be printed on a single
/// line without indentation.
}
三、编译及运行示例代码
编译:
g++ -o json-maker json-maker.cpp --std=c++17 -l PocoJSON -l PocoFoundation -I /usr/local/include/
运行:
$ LD_LIBRARY_PATH=/usr/local/lib ./json-maker
{"key":"value","sub":{"subkey":"subvalue"}}
注意:如果 poco 安装在了 /usr/ 目录中,那么就不需要 LD_LIBRARY_PATH 环境变量了,如果安装在了其它地方,那就需要使用 LD_LIBRARY_PATH 指定 poco 动态链接库所在的位置。