在 Ubuntu 14.04:
$ sudo apt-get install libjsoncpp-dev
$ g++ -I/usr/include/jsoncpp/ main.cpp -ljsoncpp
在 Mac OS X 10.10.1 搭配 MacPorts 管理:
$ sudo port install jsoncpp
$ g++ -std=c++11 -I/opt/local/include/ -L/opt/local/lib main.cpp -ljsoncpp
由於都可以透過系統常見的管理工具安裝,即可省去下載 source code 編譯等管理成本。簡易範例:
$ vim example.cpp
#include <iostream> // std::cout
#include <string> // std::string
#include <json/json.h>
int main() {
std::string raw = "{\"key\":\"value\",\"我\":\"是誰\",\"array\":[\"a\",\"b\",123]}";
Json::Reader reader;
Json::Value value;
std::cout << "Input: " << raw << std::endl;
if (reader.parse(raw, value)) {
std::cout << "parsing: " << value ;//<< std::endl;
std::cout << "get: " << value["我"] ;//<< std::endl;
std::string data = value["key"].asString();//toStyledString();
std::cout << "string: [" << data << "]" << std::endl;
// with -std=c++11
std::cout << "---" << std::endl;
for (auto it : value) {
std::cout << "elm: " << it ;//<< std::endl;
if (it.isArray()) {
for (auto it2 : it)
std::cout << "array data: " << it2 ;//<< std::endl;
}
}
}
return 0;
}
$ g++ -I/opt/local/include/ -L/opt/local/lib main.cpp -ljsoncpp
$ ./a.out
Input: {"key":"value","我":"是誰","array":["a","b",123]}
parsing:
{
"array" : [ "a", "b", 123 ],
"key" : "value",
"我" : "是誰"
}
get: "是誰"
string: [value]
---
elm: [ "a", "b", 123 ]
array data: "a"
array data: "b"
array data: 123
elm: "value"
elm: "是誰"
沒有留言:
張貼留言