目录
一、获取 poco 源码
git clone https://github.com/pocoproject/poco.git
如果 clone 的时候网速慢,可以尝试 clone 命令的多线程参数:-j
git clone -j 10 https://github.com/pocoproject/poco.git
二、编译 poco
cd poco/ # 进入 clone 下来的 poco 目录
cmake . # 执行 cmake 命令
./configure # 执行 configure 命令
make # 执行 make 命令开始编译
make install # install 编译后的文件,默认安装到 /usr/local 目录中
如果不想把 poco 安装在 /usr/local 中,可以在执行 configure 命令的时候,指定安装位置,例如安装到 /usr 目录(不过经过测试,貌似不好使啊!):
./configure --prefix=/usr
三、使用 poco 库中的 JSON模块
编译完成后,就可以使用 poco 库了。
一个简单的测试JSON的代码如下:
#include <Poco/JSON/Parser.h>
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
std::string json = "{ \"test\" : { \"property\" : \"value\", \"dog\": \"cat\" } }";
Poco::JSON::Parser parser;
Poco::Dynamic::Var result = parser.parse(json);
Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>();
Poco::Dynamic::Var test = object->get("test");
std::cout << "---test object to string : \n" << test.toString() << std::endl;
Poco::JSON::Object::Ptr subObject = test.extract<Poco::JSON::Object::Ptr>();
test = subObject->get("property");
std::string val = test.toString();
std::cout << "---get 'property' : " << val << std::endl;
Poco::DynamicStruct ds = *object;
val = ds["test"]["dog"].toString();
std::cout << "---get 'dog' : " << val << std::endl;
return 0;
}
编译:
g++ -o json-parser json-parser.cpp -l PocoJSON -l PocoFoundation -I /usr/local/include/
执行:json-parser
$ LD_LIBRARY_PATH=/usr/local/lib ./json-parser
---test object to string :
{
"dog" : "cat",
"property" : "value"
}
---get 'property' : value
---get 'dog' : cat
执行 json-parser 的时候加 LD_LIBRARY_PATH 环境变量的目的,是让 json-parser 去 LD_LIBRARY_PATH 中找动态链接库。