推荐一款cpp解析json工具--rapidjson

项目地址:http://code.google.com/p/rapidjson/

上面有很详细的介绍:http://code.google.com/p/rapidjson/wiki/UserGuide

作者介绍说:" Rapidjsonis an attempt to create the fastest JSON parser and generator. "

这是一个试图创造出一个最快的json解析和生成项目 呵呵。

 

嘛也不说 通过一个例子来看看这个工具的好用之处。

#include "rapidjson/document.h"	// rapidjson's DOM-style API
#include "rapidjson/prettywriter.h"	// for stringify JSON
#include "rapidjson/filestream.h"		// wrapper of C stream for prettywriter as output
#include <cstdio>

using namespace rapidjson;

int main()
{     
	char json[100] = "{ \"hello\" : \"world\" }"; 
	rapidjson::Document d;     
	d.Parse<0>(json);      
	printf("%s\n", d["hello"].GetString());    
	printf("%s\n", json);    
	getchar();
	return 0; 
}

 

输出:



下面说说这个开源程序的几个特点:

优点:

1.依赖库很少,

2.轻量级

3.对于Dom模型层级关系表述的很清楚

 

缺点:

1。只支持标准的json格式,一些非标准的json格式不支持

2。缺少一些比较通用的接口,再解析的时候需要自己再封装一层,否则代码量将会很大。

 

举个例子:

Json数据

{ "hello" : "world","t" : true , "f" : false, "n": null,"i":123, "pi": 3.1416, "a":[1, 2, 3, 4] }

 

为了获取a中第三个元素的值就得进行如下的操作:

int main()
{     
	//char json[100] = "{ \"hello\" : \"world\" }"; 
	
	const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";

	rapidjson::Document d;     
	d.Parse<0>(json);      
	if (d.HasParseError())
	{
		printf("GetParseError %s\n",d.GetParseError());
	}

	if (d.HasMember("a"))//这个时候要保证d湿IsObject类型 最好是 if(d.Isobject() && d.HasMember("a"))
	{
		const Value &a=d["a"];
		if (a.IsArray() && a.Size() > 3)
		{
			const Value &a3=a[2];
			string stra3;
			ValueToString(a3, stra3);
			if (a3.IsInt())
			{
					printf("GetInt [%d] \n",a3.GetInt()); ;
			}
		}
	}
	
	getchar();
	return 0; 
}

可以看到为了获取一个二级的数据需要进行一层层的解析和类型判断,否则程序就会崩溃。

这里注意的一点HasMember 也必须是Isobject才能调用否则程序也会调用失败。

建议可以封装出以下几个接口:

int ValueToString(const Value &node ,string &strRet);

int ValueToLong(const Value &node ,long &lRet);

int GetChildNode(const Value &Pnode,vector<string> &listCfg, Value &ChildNode ) ;

int GetChildNode(const Value &Pnode,const intiArrSize, char[][32] &szArrCfg, Value &ChildNode ) ;

之类的接口。


 源码下载

不对之处敬请谅解~~ 欢迎交流~~~微笑




评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值