cpp文件
#include "HelloWorldScene.h"
#include "CocoStudio/Json/rapidjson/document.h"
USING_NS_CC;
USING_NS_CC_EXT;
using namespace std;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
initHttpClinet();
return true;
}
void HelloWorld::initHttpClinet(){
CCHttpClient* cinet=CCHttpClient::getInstance();
CCHttpRequest* request=new CCHttpRequest();
request->setUrl("http://gc.ditu.aliyun.com/regeocoding?type=111&l=31,117");
request->setResponseCallback(this,httpresponse_selector(HelloWorld::requestCallBack));
request->setRequestType(CCHttpRequest::kHttpGet);
cinet->send(request);
}
void HelloWorld::requestCallBack(CCHttpClient* client, CCHttpResponse* response){
CCLOG("requestCallBack");
std::vector<char>* buffer=response->getResponseData();
/*std::stringstream oss;
for(unsigned int i=0;i < buffer->size();i++){
oss<<(*buffer)[i];
}
string temp=oss.str();
const char * buf=temp.c_str(); */
char* responseString = new char[buffer->size() + 1];
std::copy(buffer->begin(), buffer->end(), responseString);
parseJsonString(responseString);
CCLOG("data:%s",responseString);
}
//不明白为什么下载到的认为不是json格式的
void HelloWorld::parseJsonString(char * str){
//{"queryLocation":[31,117],"addrList":[{"type":"street","status":1,"name":"011县道","admCode":"340881","admName":"安徽省,安庆市,桐城市","addr":"","nearestPoint":[116.99050,31.00059],"distance":951.830},{"type":"poi","status":1,"name":"吴店","id":"ANB022C02WPQ","admCode":"340881","admName":"安徽省,安庆市,桐城市,","addr":"","nearestPoint":[116.99655,30.99813],"distance":392.421},{"type":"doorPlate","status":0,"name":"","admCode":"","admName":"","nearestPoint":[],"distance":-1}]}
str="{ \"hello\" : \"world\" }";
CCLOG("data:%s",str);
rapidjson::Document d;
d.Parse<0>(str);
if (d.HasParseError()) //解析错误
{
CCLOG("GetParseError %s\n",d.GetParseError());
return;
}
if(d.HasMember("queryLocation")&&d["queryLocation"].IsArray()){
rapidjson::Value& location=d["queryLocation"];
for (unsigned int i=0;i<location.Size();i++)
{
rapidjson::Value& val=location[i];
CCLOG("val:%d",val.GetInt());
}}
if(d.HasMember("hello")){
CCLOG("val:%s",d["hello"].GetString());
}
}