从json格式的字符串中解析读:
//g++ jsoncpp_read_sample.cpp -I/usr/local/include/jsoncpp -ljsoncpp #include <iostream> #include <string> #include <json/json.h> int main(void) { std::string strjson = "{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\"},{\"key2\":\"value3\"},{\"key2\":\"value4\"}]}"; /* { "key1":"value1","array": [ {"key2":"value2"},{"key2":"value3"},{"key2":"value4"} ] } */ Json::Reader reader; Json::Value root; if (reader.parse(strjson,root)) { std::string out = root["key1"].asString(); std::cout << out << std::endl; const Json::Value arrayObj = root["array"]; for (int i=0; i<arrayObj.size(); i++) { out = arrayObj[i]["key2"].asString(); std::cout << out << std::endl; } } return 0; }
//g++ jsoncpp_write_sample.cpp -I/usr/local/include/jsoncpp -ljsoncpp #include <iostream> #include <string> #include <json/json.h> int main(void) { Json::Value root; Json::Value arrayObj; Json::Value item; for (int i = 0; i < 10; i ++) { item["key"] = i; arrayObj.append(item); } root["key1"] = "value1"; root["key2"] = "value2"; root["array"] = arrayObj; //root.toStyledString(); //格式化输出Json格式内容 std::string out = root.toStyledString(); std::cout << out << std::endl; std::cout << "--------------------" << std::endl; //未格式化输出Json格式内容 Json::FastWriter writer; std::string json_str = writer.write(root); std::cout << json_str << std::endl; return 0; }
从json格式的文件中解析读:
{ "mmac": "e4:95:6e:4e:ed:6e","wmac": "ff:ff:ff:ff:ff:ff","data": [ { "mac": "3c:46:d8:19:6a:e3","RSSi": "-82","tmc": "ff:ff:ff:ff:ff:ff" },{ "mac": "90:18:7c:f2:45:cc","RSSi": "-71","tmc": "ff:ff:ff:ff:ff:ff" },{ "mac": "b8:44:d9:02:b0:94","RSSi": "-86",{ "mac": "dc:85:de:6a:f8:37","RSSi": "-44",{ "mac": "ec:0e:c4:60:b7:95","RSSi": "-77","tmc": "ff:ff:ff:ff:ff:ff" } ] }
//g++ read_json_file.cpp -I/usr/local/include/jsoncpp -ljsoncpp #include <fstream> #include <iostream> #include <string> #include <cassert> #include <json/json.h> int main(void) { std::ifstream ifs; ifs.open("test.json"); assert(ifs.is_open()); Json::Reader reader; Json::Value root; if (!reader.parse(ifs,root,false)) { std::cout<<"reader.parse() fail"<<std::endl; return -1; } std::string out = root["mmac"].asString(); std::cout << "mmac " << out << std::endl; out = root["wmac"].asString(); std::cout << "wmac " << out << std::endl; const Json::Value arrayObj = root["data"]; for (int i=0; i<arrayObj.size(); i++) { out = arrayObj[i]["mac"].asString(); std::cout << "data-->mac " << out << std::endl; out = arrayObj[i]["RSSi"].asString(); std::cout << "data-->RSSi " << out << std::endl; out = arrayObj[i]["tmc"].asString(); std::cout << "data-->tmc " << out << std::endl; } return 0; }