json的解析
1 #include <stdio.h> 2 #include <string> 3 using namespace std; 4 5 /* jsoncpp support */ 6 #include "jsoncpp/json.h" // JSON构造与解析 7 8 9 // 从文件中读取字符串 10 string readfile (const char* filename) 11 { 12 FILE* fp = fopen(filename, "rb"); 13 if(!fp) //检查文件是否错误 14 { 15 printf("failed to open file! file: %s" , filename); 16 return ""; 17 } 18 char* buf = new char[1024*16]; //新建缓冲区 19 int n = fread(buf, 1, 1024*16, fp); 20 fclose(fp); 21 22 string result; 23 if(n >= 0) 24 result.append(buf, 0, n); 25 delete [] buf; 26 27 return result; 28 } 29 30 int parseJSON (const char* jsonstr) 31 { 32 Json::Reader reader; 33 Json::Value resp; 34 if (!reader.parse(jsonstr, resp, false)) 35 throw string("bad json format!\n"); 36 37 int errorCode = resp["errorCode"].asInt(); 38 string reason = resp["reason"].asString(); 39 if(errorCode != 0) 40 throw string(reason); 41 42 Json::Value& result = resp["result"]; 43 if(result.isObject()) 44 { 45 int userId = result["userId"].asInt(); 46 string name = result["name"].asString(); 47 printf("userId:%d, name: %s\n", userId, name.c_str()); 48 } 49 printf("show numbers:\n"); 50 Json::Value& numbers = resp["numbers"]; 51 for(int i=0; i<numbers.size() ; i++) 52 { 53 Json::Value& jvalue = numbers[i]; 54 int n = jvalue.asInt(); 55 printf("%d ,", n); 56 } 57 58 return 0; 59 } 60 61 62 int main() 63 { 64 string jsonstr = readfile("example.json"); 65 // printf("%s", jsonstr.c_str()); 66 67 /* 使用异常机制会方便一些 */ 68 try{ 69 parseJSON(jsonstr.c_str()); 70 }catch(string e) 71 { 72 printf("解析错误: %s \n", e.c_str()); 73 } 74 return 0; 75 }
posted on 2017-12-13 23:55 Doctor_uee 阅读(237) 评论(0) 收藏 举报
浙公网安备 33010602011771号