推荐一款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解析和生成项目 呵呵。

 

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

[html]  view plain copy print ?
  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中第三个元素的值就得进行如下的操作:

[html]  view plain copy print ?
  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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 中解析 JSON 字符串,可以使用第三方的 JSON 库,例如:RapidJSON、nlohmann/jsonJsonCpp 等等。 以 RapidJSON 为例,示例代码如下: ```c++ #include <iostream> #include "rapidjson/document.h" int main() { const char* json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; rapidjson::Document doc; doc.Parse(json); std::string name = doc["name"].GetString(); int age = doc["age"].GetInt(); std::string city = doc["city"].GetString(); std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "City: " << city << std::endl; return 0; } ``` 以上代码中,首先定义 JSON 字符串 `json`,然后使用 `rapidjson::Document` 对象解析 JSON 字符串,通过 `GetString()` 和 `GetInt()` 等函数获取 JSON 中的值。需要注意的是,以上示例只能解析简单的 JSON 数据,对于复杂的 JSON 结构,需要使用更多的 RapidJSON API。 另外,如果 JSON 字符串存储在 char* 中,也可以使用 `rapidjson::MemoryStream` 对象进行解析,示例代码如下: ```c++ #include <iostream> #include "rapidjson/document.h" #include "rapidjson/reader.h" struct MyHandler { bool String(const char* str, rapidjson::SizeType length, bool copy) { std::string value(str, length); std::cout << "String: " << value << std::endl; return true; } bool Int(int i) { std::cout << "Int: " << i << std::endl; return true; } bool Bool(bool b) { std::cout << "Bool: " << b << std::endl; return true; } }; int main() { const char* json = "{\"name\":\"John\",\"age\":30,\"isMale\":true}"; rapidjson::MemoryStream ms(json, strlen(json)); rapidjson::Reader reader; MyHandler handler; reader.Parse(ms, handler); return 0; } ``` 以上代码中,定义了一个自定义的 `MyHandler` 类,实现了 RapidJSON 的 `BaseReaderHandler` 接口,通过重写接口中的函数,实现对 JSON 数据的解析。然后使用 `rapidjson::MemoryStream` 对象将 char* 转化为流对象,使用 `rapidjson::Reader` 对象解析 JSON 数据,并通过 `MyHandler` 类处理解析后的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值