C++学习笔记-利用rapidJSON读取JSON数据
生活随笔
收集整理的這篇文章主要介紹了
C++学习笔记-利用rapidJSON读取JSON数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JSON文件如下:
{"errorCode":0,"reason":"OK","result":{"userId":10086,"name":"中國移動"},"numbers":[110,120,119,911] }目錄結構如下:
程序運行截圖如下:
?
源碼如下:
#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; }int main(){string jsonstr = readfile("example.json");//parseJSON(jsonstr.c_str());try{parseJSON2(jsonstr.c_str());}catch(string e){printf("error: %s \n", e.c_str());}getchar();return 0; }?
總結
以上是生活随笔為你收集整理的C++学习笔记-利用rapidJSON读取JSON数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++\Python\Qt工作笔记-读取
- 下一篇: C++工作笔记-3种方法对数据类型进行拆