json C++ 待完善

目录

3、c++  rapidjson 处理json方法:

rapidjson 的使用--简单的字典形式

编码:转换成字符结构

编码复杂的字典结构--字典中带有字典和列表

解码


 

 

 

 

json的官网:包含所有语言  http://json.org/

3、c++  rapidjson 处理json方法:

和python不一样:python自带的内置模块很好的处理json数据。c++必须要上官网下载头文件以及相应的cpp文件才可以。

去官网找发现有许多api函数库,这里我们选择阿发你好推荐的rapidjson库。

在vs2008和vs2012上面都通过了,源码复制过去的,文件复制过去的,一动没动。

这里复习一下vs的使用方法:

1,新建win32控制台程序--》空项目--》新建main.cpp文件

2,将json函数库导入和main.cpp一个目录里---》在vs界面工程中新建添加筛选器,将json下载的文件添加进来(包括头文件和cpp文件)

下面写入main.cpp的代码

/* rapid json support */
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;

/* stl support*/
#include <iostream>
#include <string>
using namespace std;



// 从文件中读取字符串
string readfile (const char* filename)
{
	FILE* fp = fopen(filename, "rb");
	if(!fp)
	{
		printf("failed to open file! 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) //这个函数是改进的parseJSON2 ,用异常提示用户那里错误了
{
	Document d;
	if (d.Parse(jsonstr).HasParseError())
		throw string("parse error!");
	if(!d.IsObject())
		throw string("should be an object!\n");
	
	if(!d.HasMember("errorCode"))
		throw string("'errorCode' not 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()
{
        //将文本中的json结构读取进来,并打印出来看看
	string jsonstr = readfile("example.json");
	printf("%s", jsonstr.c_str());
        
        //解码:将文本的数据转换成数值型的了。
	parseJSON(jsonstr.c_str());


// 	try{
// 		parseJSON2(jsonstr.c_str());		
// 	}catch(string& e)
// 	{
// 		printf("解析错误: %s \n", e.c_str());
// 	}
	return 0;
}


rapidjson 的使用--简单的字典形式

编码:转换成字符结构

    {
        "id": 1001,
        "name": "shaofa"
        "login": true,
        "extras": null
    }


// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <string>
using namespace std;
using namespace rapidjson;

string toString(const Document& d)
{
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);
	string str = buffer.GetString();
	return str;
}
int main() {

	Document d; # 设置一个json框架,
	Document::AllocatorType& allocator = d.GetAllocator();//引用一个内存管理对象,不用管为什么,照抄就可以
	d.SetObject();//这句话很关键,是设置成字典结构

	d.AddMember("id", 1001, allocator);//添加一个成员
	d.AddMember("name", "shaofa", allocator);
	d.AddMember("login", true, allocator);

	string str = toString(d); //转换成字符结构
	printf(str.c_str());

	return 0;
}

编码复杂的字典结构--字典中带有字典和列表

{
    "errorCode": 0,
    "reason": "OK",
    "result":
    {
        "userId": 10099380,
        "name": "shaofa"
    },
    "numbers": [ 123, 122, 238, 089 ]
}


#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;

/* stl support*/
#include <iostream>
#include <string>
using namespace std;

string toString(const Document& d)
{
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);
	string str = buffer.GetString();
	return str;
}

int main()
{
	Document d;
	Document::AllocatorType& allocator = d.GetAllocator();
	d.SetObject(); // 第一层次,document有两种表示方式:一个是{}形式,一种是[]形式
	// SetObject是表示设置成{}形式

	d.AddMember("errorCode", 0, allocator);
	d.AddMember("reason", "OK", allocator);

        //添加复杂的成员
	if(1)
	{
		Value v; //创建一个复杂的成员
		v.SetObject();//设置这个复杂成员为字典结构
		v.AddMember("userId", 10099380,allocator);//添加成员
		v.AddMember("name", "shaofa", allocator);

		d.AddMember("result", v, allocator);//将这个复杂的字典结构添加到上一层中
	}

	if(1)
	{
		Value v;
		v.SetArray(); //将这个复杂的结构设置为列表形式
		v.PushBack(123, allocator);
		v.PushBack(122, allocator);
		v.PushBack(238, allocator);
		v.PushBack(89, allocator);

		d.AddMember("numbers", v, allocator);
	}

	string str = toString(d);
	printf(str.c_str());

	return 0;
}


解码

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值