在网上找了半天c++怎么调用json,发现大部分都是使用jsoncpp。但是jsoncpp需要先建立静态链接才能使用,也就是说,需要相同环境下,才能编译。而其他的库在vs2013上都不太能使用。
于是在我找了一天后,终于找到一个能在vs2013上使用的json库。得益于这个库大部分都是使用C语言来实现的。所以在现在大部分的环境下都能运行。可惜的是,这个库读取到的json文件,是转化为一棵树(这颗树还挺深的,而且与现在的大部分读取json代码格格不入,非常别扭)。
于是,我只能自己封装一下这个库,把他转化为我们现在比较熟悉的写法。
首先将json.h和json.cpp移动到你的根目录下,然后将这两个文件拉到你的解决方案资源管理器中。
具体的使用方法就如下所示。
可以使用文件读写
//都在JsonAdapterd对象中
//传入文件路径
loadJsonFile(string path);
//传入字符串
stringToJson(string str);
json:
[
{
"nId": 1001,
"strName": "新手村",
"nMaxRow": 20,
"nMaxCol": 15,
"nBirthRow": 5,
"nBirthCol": 5,
"transfer": [
{
"nRow": 11,
"nCol": 10,
"nextId": 1002
}
]
},
{
"nId": 1002,
"strName": "高手村",
"nMaxRow": 20,
"nMaxCol": 15,
"nBirthRow": 1,
"nBirthCol": 1,
"transfer": [
{
"nRow": 11,
"nCol": 10,
"nextId": 1001
},
{
"nRow": 4,
"nCol": 4,
"nextId": 1003
}
]
}
]
读取方式:
#include "json.h"
void CMapDtMgr::loadFile(const string& strPath)
{
//传入路径,拿到适配器
auto aj = new JsonAdapter(strPath);
//拿到json对象
auto ab = aj->getJsonObject();
//getArraySize(): 拿到json对象的array的大小
//operator[] 拿到json对象中array的json对象
//getObject(key_value); 拿到对象
//getInteger(key_value); 拿到整数
//getBool(key_value);拿到bool
//getDouble(key_value): 拿到复数
//getString(key_value):拿到字符串
//拿到对象例子
// jb[0].getObject("friend");
for(int i = 0; i < ab.getArraySize(); i++)
{
auto mapDt = new CMapDt();
mapDt->nId = ab[i].getInteger("nId");
mapDt->nMaxRow = ab[i].getInteger("nMaxRow");
mapDt->nMaxCol = ab[i].getInteger("nMaxCol");
mapDt->nBirthRow = ab[i].getInteger("nBirthRow");
mapDt->nBirthCol = ab[i].getInteger("nBirthCol");
mapDt->strName = ab[i].getString("strName");
mapDt->pArrMap = new int *[mapDt->nMaxRow];
for(int j = 0; j < mapDt->nMaxRow; j++)
{
mapDt->pArrMap[j] = new int[mapDt->nMaxCol];
}
for(int j = 0; j < mapDt->nMaxRow; j++)
{
for(int k = 0; k < mapDt->nMaxCol; k++)
{
if(j == 0 || k == 0 || j == mapDt->nMaxRow - 1 || k == mapDt->nMaxCol - 1)
mapDt->pArrMap[j][k] = 1;
else
mapDt->pArrMap[j][k] = 0;
}
}
auto nextObj = ab[i].getObject("transfer");
for(int j = 0; j < nextObj.getArraySize(); j++)
{
int nRow = nextObj[j].getInteger("nRow");
int nCol = nextObj[j].getInteger("nCol");
int nextId = nextObj[j].getInteger("nextId");
mapDt->pArrMap[nRow][nCol] = nextId;
}
m_vecDatas.push_back(mapDt);
}
}