加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsoncpp的一些使用方法介绍

发布时间:2020-12-16 19:22:24 所属栏目:百科 来源:网络整理
导读:jsoncpp的一些使用方法介绍: 1、初始化 Json::Value root; Json::Reader reader; reader.parse(“{“name”:”sunny”}”,root); Reader可以用来初始化一个人json从字符串。 2、读取json文件初始化 这是我写的一个方法: Json::Value BYJsonDataManager::ge
jsoncpp的一些使用方法介绍:

1、初始化

Json::Value root;

Json::Reader reader;

reader.parse(“{“name”:”sunny”}”,root);

Reader可以用来初始化一个人json从字符串。

2、读取json文件初始化

这是我写的一个方法:

	Json::Value BYJsonDataManager::getJsonFromFile(const char* fileName){
		Json::Reader reader;
		ifstream file(getFullPath(fileName));
		CCAssert(file.is_open(),"file is open fail!");
		Json::Value root;
		if  (!reader.parse(file,root,false )) {
			CCAssert(false,"Json::Reader Parse error!");
		}
		return root;
	}

3、解析json

首先生成一个json

Json::Value myjson = getJsonFromFile(“test.json”); //利用上面的函数生成一个json。

int num = myJson["num"].asInt();

string str = myJson["name"].asString();


4、json数组

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函数生成一个json。

int i = 0;

Json::Value arr = myjson[i]; //获取arr数组的第一个元素


5、利用迭代器获取json的key。(有时候并不知道json的key,这个时候可以利用迭代器获取json的key)

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函数生成一个json。

Json::Value::Members members(myjson.getMemberNames());

for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
const std::string &key = *it;
}

6、自己拼装Json数组,(有时候发往服务器的数据是一个json数据)

Json::Value arr;

for(int i = 0 ;i < 5;++i){

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函数生成一个json。

arr.append(protocolData);

}

如果想让这个jsonArr有key。

Json::Value arr2;

arr2["array"] = arr;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读