jsoncpp的一些使用方法介绍

来源:互联网 发布:c语言教程全套 编辑:程序博客网 时间:2024/05/17 20:22
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;