Instantly share code, notes, and snippets.

Embed
What would you like to do?
CCHttpとJsonでサーバー通信
void GameScene::main {
CCHttpRequest* request = newCCHttpRequest();
request->setUrl("http://sample.com");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, callfuncND_selector(GameScene::onHttpRequestCompleted));
request->setTag("GET sample");
CCHttpClient::getInstance()->send(request);
request->release();
}
void GameScene::onHttpRequestCompleted(CCNode *sender, void *data)
{
CCHttpResponse *response = (CCHttpResponse*)data;
CCHttpRequest *request = response->getHttpRequest();
// レスポンスデータ
std::vector<char> *buffer = response->getResponseData();
// &(*buffer)[0]にフルのJson文字列が入ってる。[1]は前の1文字がない。以下2,3,4と文字列が減っていく。
// jsonの取得方法あってる?
Json* json = Json_create(&(*buffer)[0]);
// String型
printf("name:%s,", Json_getString(json, "name", ""));
// int型
printf("age:%d,", Json_getInt(json, "age", 0));
// リストも受け取れます
Json* jsonList = Json_getItem(json, "list");
for (int i = 0; i < Json_getSize(jsonList); i++) {
printf("list[%d]: %d", i, Json_getItemAt(jsonList, i)->valueint);
}
}
//サーバーから返すデータは{"name":"Ken","age":19,"list":[1,2,3]}
// ログ
// name :Ken,age: 19,list[0]: 1,list[1]: 2,list[2]: 3,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment