rapidjson 使用教程

     在cocos2d-x引入了rapidjson,它处理速度比其他的json库快,反正不管了,我们这边只是学习下如何使用。rapidjson官方网址: https://code.google.com/p/rapidjson/wiki/UserGuide,上面有wiki有部分说明文档,可以看下。

github仓库地址:https://github.com/miloyip/rapidjson

下面我们讲讲rapidjson读写文件。

直接贴代码

TestJson.h

 1 #ifndef _TEST_JSON_H_
 2 #define _TEST_JSON_H_
 3 
 4 #include "json/document.h"
 5 using namespace std;
 6 class TestJson
 7 {
 8 public:
 9     TestJson(void);
10     ~TestJson(void);
11     //读取文件
12     void readFile( const char * fileName );
13     //添加字符串成员
14     void addStrMenber(const char *key,const char *value);
15     //是否存在成员
16     bool hasMenber(const char *key);
17     //删除成员
18     void removeMenber(const char *key);
19     //写入文件
20     bool writeFile( const char * fileName );
21 
22 private:
23     rapidjson::Document _jsonDocument;
24 };
25 #endif

 

TestJson.cpp

 1 #include "TestJson.h"
 2 #include <stdio.h>
 3 #include "json/filestream.h"
 4 #include "json/stringbuffer.h"
 5 #include "json/writer.h"
 6 TestJson::TestJson(void)
 7 {
 8 }
 9 
10 TestJson::~TestJson(void)
11 {
12 }
13 
14 void TestJson::readFile( const char * fileName )
15 {
16     if (fileName == nullptr) return;
17     FILE * pFile = fopen (fileName , "r");
18     if(pFile){
19         //读取文件进行解析成json
20         rapidjson::FileStream inputStream(pFile);
21         _jsonDocument.ParseStream<0>(inputStream);
22         fclose(pFile);
23     }
24     if(!_jsonDocument.IsObject()){
25         _jsonDocument.SetObject();
26     }
27 }
28 
29 void TestJson::addStrMenber(const char *key,const char *value)
30 {
31     rapidjson::Value strValue(rapidjson::kStringType);
32     strValue.SetString(value,_jsonDocument.GetAllocator());
33     _jsonDocument.AddMember(key,strValue,_jsonDocument.GetAllocator());
34 }
35 
36 bool TestJson::hasMenber(const char *key)
37 {
38     if (_jsonDocument.HasMember(key)) {
39         return true;
40     }
41     return false;
42 }
43 
44 void TestJson::removeMenber(const char *key)
45 {
46     if (_jsonDocument.HasMember(key)) {
47         _jsonDocument.RemoveMember(key);
48     }
49 }
50 
51 bool TestJson::writeFile( const char * fileName )
52 {
53     if (fileName == nullptr) return false;
54     //转为字符串格式
55     rapidjson::StringBuffer buffer;
56     rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
57     _jsonDocument.Accept(writer);
58     const char* str = buffer.GetString();
59     FILE * pFile = fopen (fileName , "w");
60     if (!pFile) return false;
61     fwrite(str,sizeof(char),strlen(str),pFile);
62     fclose(pFile);
63     return true;
64 }

 

转载于:https://www.cnblogs.com/chuanwei-zhang/p/3930731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值