https://blog.csdn.net/what951006/article/details/78864615
最近在工作的过程中遇到前端代码写得太慢了,无法提供真正的数据给后端进行调试,只好自己动手去造一些数据来进行测试,保证开发任务能早日完成。
需要的数据类型大致是如下所示:
"array": [
{
"id": 0,
"name": "test"
},
{
"id": 1,
"name": "test"
},
{
"id": 2,
"name": "test"
}
]
Json::Value arrayObj; // 构建对象
for (int i = 0; i < 3; i++)
{
Json::Value new_item;
new_item["id"] = i + 1;
new_item["name"] = "test";
//组装数组的时候,需要使用append
arrayObj["array"].append(new_item);
}
std::string strData = arrayObj.toStyledString();
map<int, std::string> cameraInfoMap;
Json::Reader readerinfo;
Json::Value root;
if (readerinfo.parse(strData, root))
{
if (root["array"].isArray())
{
int nArraySize = root["array"].size();
for (int i = 0; i < nArraySize; i++)
{
int nID = root["array"][i]["id"].asInt();
std::string strName = root["array"][i]["name"].asString();
cameraInfoMap[nID] = strName;
}
}
}
测试代码采用上述方式是可以正常构造与解析出来的,如果采用如下的方式,容易出问题,建议不要采用下面构造数据的方式:
const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
{
std::string upload_id = root["uploadid"].asString(); // 访问节点,upload_id = "UP000000"
int code = root["code"].asInt(); // 访问节点,code = 100
}
第一种方法比较简单,第二种方法有时候容易出错,就没必要去采用了。