C語言
參考 https://linuxprograms.wordpress.com/2010/05/20/json-c-libjson-tutorial/使用終端機
- 首先安裝需要的package
- 利用以下的測試程式來測試環境
#include <json/json.h> #include <stdio.h> int main() { char * string = "{"name" : "joys of programming"}"; json_object * jobj = json_tokener_parse(string); enum json_type type = json_object_get_type(jobj); printf("type: ",type); switch (type) { case json_type_null: printf("json_type_nulln"); break; case json_type_boolean: printf("json_type_booleann"); break; case json_type_double: printf("json_type_doublen"); break; case json_type_int: printf("json_type_intn"); break; case json_type_object: printf("json_type_objectn"); break; case json_type_array: printf("json_type_arrayn"); break; case json_type_string: printf("json_type_stringn"); break; } }
3. 編譯 gcc json_type.c -l json
使用Eclipse
- 建立一個C專案,將上列測試程式加到專案中。
- 點專案再按右鍵->Properties->C/C++ General->Paths and Symols ->Includes加入/usr/include/json
- 接下來選C/C++ Build->Settings->GCC C++ Linker->Libraries加入json
C++語言
- 安裝需要的package # sudo apt-get install libjsoncpp-dev (ubuntu)
- 建立一個C++專案將下列程式碼加入
#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;
}
#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;
}
3. 點專案再按右鍵->Properties->C/C++ General->Paths and Symols ->Includes加入/usr/include/jsoncpp/json
4. 接下來選C/C++ Build->Settings->GCC C++ Linker->Libraries加入jsoncpp
5. 接下來選C/C++ Build->Settings->GCC C++ Compile->include加入/usr/include/jsoncpp/,/opt/local/include/
6. 接下來選C/C++ Build->Settings->GCC C++ Compile->Dialect->Language standard 選 ISO C++11(-std=c++0x) PS:因為這個測試函數用到C++11的語法。
沒有留言:
張貼留言