创造json数据来进行接口测试

 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 
    }

第一种方法比较简单,第二种方法有时候容易出错,就没必要去采用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值