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;
}

 

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值