微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jsoncpp的一些使用方法介绍

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;

原文地址:https://www.jb51.cc/json/290443.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐