现在的位置: 首页 > 综合 > 正文

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

2018年07月17日 ⁄ 综合 ⁄ 共 2299字 ⁄ 字号 评论关闭

项目地址: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解析和生成项目 呵呵。

 

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

  1. #include "rapidjson/document.h" // rapidjson's DOM-style API  
  2. #include "rapidjson/prettywriter.h" // for stringify JSON  
  3. #include "rapidjson/filestream.h"       // wrapper of C stream for prettywriter as output  
  4. #include <cstdio>  
  5.   
  6. using namespace rapidjson;  
  7.   
  8. int main()  
  9. {       
  10.     char json[100] = "{ \"hello\" : \"world\" }";   
  11.     rapidjson::Document d;       
  12.     d.Parse<0>(json);        
  13.     printf("%s\n", d["hello"].GetString());      
  14.     printf("%s\n", json);      
  15.     getchar();  
  16.     return 0;   
  17. }  


 

输出:


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

优点:

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中第三个元素的值就得进行如下的操作:

  1. int main()  
  2. {       
  3.     //char json[100] = "{ \"hello\" : \"world\" }";   
  4.       
  5.     const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";  
  6.   
  7.     rapidjson::Document d;       
  8.     d.Parse<0>(json);        
  9.     if (d.HasParseError())  
  10.     {  
  11.         printf("GetParseError %s\n",d.GetParseError());  
  12.     }  
  13.   
  14.     if (d.HasMember("a"))//这个时候要保证d湿IsObject类型 最好是 if(d.Isobject() && d.HasMember("a"))  
  15.     {  
  16.         const Value &a=d["a"];  
  17.         if (a.IsArray() && a.Size() > 3)  
  18.         {  
  19.             const Value &a3=a[2];  
  20.             string stra3;  
  21.             ValueToString(a3, stra3);  
  22.             if (a3.IsInt())  
  23.             {  
  24.                     printf("GetInt [%d] \n",a3.GetInt()); ;  
  25.             }  
  26.         }  
  27.     }  
  28.       
  29.     getchar();  
  30.     return 0;   
  31. }  


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

这里注意的一点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 ) ;

之类的接口。


 源码下载

转载:http://blog.csdn.net/zerolxl/article/details/8241595

抱歉!评论已关闭.