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;

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...