C++ 讀寫JSON
阿新 • • 發佈:2022-03-20
用Rapid Json
參考:http://rapidjson.org/zh-cn/
RapidJSON是騰訊開源的一個高效的C++ JSON解析器及生成器,它是隻有標頭檔案的C++庫。RapidJSON是跨平臺的,支援Windows, Linux, Mac OS X及iOS, Android。
庫:連結:https://pan.baidu.com/s/1tfKOotRbsh5PIKZeDgZfZA
提取碼:wlg6
1. 生成json
////////////// 生成JSON ////////////// #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <iostream> intView Code_tmain(int argc, _TCHAR* argv[]) { rapidjson::StringBuffer buf; rapidjson::Writer<rapidjson::StringBuffer> writer(buf); //rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buf); // it can word wrap writer.StartObject(); // Between StartObject()/EndObject(),/* writer.Key("hello"); // output a key, writer.String("world"); // follow by a value. writer.Key("t"); writer.Bool(true); writer.Key("f"); writer.Bool(false); writer.Key("n"); writer.Null(); writer.Key("i"); writer.Uint(123); writer.Key("pi"); writer.Double(3.1416); writer.Key("a"); writer.StartArray(); // Between StartArray()/EndArray(), for (unsigned i = 0; i < 4; i++) writer.Uint(i); // all values are elements of the array. writer.EndArray(); writer.EndObject(); // {"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}*/ writer.Key("country"); writer.String("中國"); writer.Key("province"); writer.StartArray(); writer.StartObject(); writer.Key("name"); writer.String("黑龍江"); writer.Key("cities"); writer.StartArray(); writer.String("哈爾濱"); writer.String("大慶"); writer.EndArray(); writer.EndObject(); writer.StartObject(); writer.Key("name"); writer.String("廣東"); writer.Key("cities"); writer.StartArray(); writer.String("廣州"); writer.String("深圳"); writer.String("珠海"); writer.EndArray(); writer.EndObject(); writer.EndArray(); writer.EndObject(); const char* s = buf.GetString();//"{"country":"中國","province":[{"name":"黑龍江","cities":["哈爾濱","大慶"]},{"name":"廣東","cities":["廣州","深圳","珠海"]}]}" std::cout << s << "\n"; return 0; }
2. 解析json
////////////////// 解析 JSON /////////////////////////// #include <iostream> #include <string> #include "rapidjson/document.h" /* { "country": "中國", "province": [ { "name": "黑龍江", "cities": ["哈爾濱","大慶"] }, { "name": "廣東", "cities": ["廣州","深圳","珠海"] }, { "name": "臺灣", "cities": ["臺北","高雄"] }, { "name": "新疆", "cities": ["烏魯木齊"] } ] } */ int _tmain(int argc, _TCHAR* argv[]) { const char* str = "{\"country\":\"中國\",\"province\":[{\"name\":\"黑龍江\",\"cities\":[\"哈爾濱\",\"大慶\"]},{\"name\":\"廣東\",\"cities\":[\"廣州\",\"深圳\",\"珠海\"]},{\"name\":\"臺灣\",\"cities\":[\"臺北\",\"高雄\"]},{\"name\":\"新疆\",\"cities\":[\"烏魯木齊\"]}]}"; rapidjson::Document document; document.Parse(str); assert(document.IsObject()); std::string s = document["country"].GetString(); const rapidjson::Value& a = document["province"]; assert(a.IsArray()); for (rapidjson::SizeType i = 0; i < a.Size(); i++) // 使用 SizeType 而不是 size_t { const rapidjson::Value& b = a[i]; assert(b.IsObject()); std::string provinceName = b["name"].GetString(); std::cout << provinceName << ": "; const rapidjson::Value& c = b["cities"]; assert(c.IsArray()); for (rapidjson::SizeType i = 0; i < c.Size(); i++) { std::string cityName = c[i].GetString(); std::cout << cityName << " "; } std::cout << "\n"; } return 0; }View Code
網上的例子:
#include <iostream> #include <string> #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" using namespace rapidjson; using namespace std; string readfile(const char *filename){ FILE *fp = fopen(filename, "rb"); if(!fp){ printf("open failed! file: %s", filename); return ""; } char *buf = new char[1024*16]; int n = fread(buf, 1, 1024*16, fp); fclose(fp); string result; if(n>=0){ result.append(buf, 0, n); } delete []buf; return result; } int parseJSON(const char *jsonstr){ Document d; if(d.Parse(jsonstr).HasParseError()){ printf("parse error!\n"); return -1; } if(!d.IsObject()){ printf("should be an object!\n"); return -1; } if(d.HasMember("errorCode")){ Value &m = d["errorCode"]; int v = m.GetInt(); printf("errorCode: %d\n", v); } printf("show numbers: \n"); if(d.HasMember("numbers")){ Value &m = d["numbers"]; if(m.IsArray()){ for(int i = 0; i < m.Size(); i++){ Value &e = m[i]; int n = e.GetInt(); printf("%d,", n); } } } return 0; } int parseJSON2(const char *jsonstr){ Document d; if(d.Parse(jsonstr).HasParseError()){ throw string("parse error!\n"); } if(!d.IsObject()){ throw string("should be an object!\n"); } if(!d.HasMember("errorCode")){ throw string("'errorCode' no found!"); } Value &m = d["errorCode"]; int v = m.GetInt(); printf("errorCode: %d\n", v); printf("show numbers:\n"); if(d.HasMember("numbers")){ Value &m = d["numbers"]; if(m.IsArray()){ for(int i = 0; i < m.Size(); i++){ Value &e = m[i]; int n = e.GetInt(); printf("%d", n); } } } return 0; } /* //path="/Users/macname/Desktop/example.json" { "errorCode":0, "reason":"OK", "result":{"userId":10086,"name":"中國移動"}, "numbers":[110,120,119,911] } */ int main(){ string jsonstr = readfile("/Users/macname/Desktop/example.json"); //parseJSON(jsonstr.c_str()); try{ parseJSON2(jsonstr.c_str()); }catch(string e){ printf("error: %s \n", e.c_str()); } getchar(); return 0; } 輸出 errorCode: 0 show numbers: 110120119911View Code