您的位置:首页 > Web前端 > JavaScript

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

2014-05-15 14:42 357 查看
项目地址: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
plaincopyprint?

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

[html] view
plaincopyprint?

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

之类的接口。

 源码下载

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



原文地址:http://blog.csdn.net/zerolxl/article/details/8241595
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: