void SampleClient::OnAnEvent(sio::event &event){ //イベント名は一応event.get_name()で取得できる std::string name=event.get_name(); //データはevent.get_message()で取得できる sio::message::ptr data=event.get_messages().to_array_message(); //JSON.hをincludeしていればデータもこの型のまま文字列として出力できる std::cout<<"'"<<name<<"',"<<data<<std::endl; //JSONならばmap=data->get_mapJSON’ has()で子要素のmapを取得できる //ptr=map["key"]でキーkeyに対応する値(のポインタ)が得られるので、型に合わせてptr->get_int()のように実際の値を得る //一気に書くと以下のような感じ //cnt=data->get_map()["cnt"]->get_int(); //JSONデータを送信する /*{'platform':"C++",'Data':[1,2,"string"]}*/ client.socket()->emit("an event",JSON() .add("Integer with explicit cast",(int64_t)1) .addInt("Integer with special method",2) .add("Double",1.0/3.0) .add("String","C++") .add("Array",Array() .addInt(1) .add((int64_t)2) .add("string")) .add("Child JSON",JSON() .add("Child","JSON")) .pack()); }
/* * Set the game state according to the given JSON * game: the game state to set * json: a JSON representation of the game state */ void SetGameState(GameState *game, cJSON *json) { game->round_id = JSON_INT(json, "round_id"); game->initial_stack = JSON_INT(json, "initial_stack"); game->stack = JSON_INT(json, "stack"); game->current_bet = JSON_INT(json, "current_bet"); game->call_amount = JSON_INT(json, "call_amount"); game->phase = GetPhase(JSON_STRING(json, "betting_phase")); game->your_turn = JSON_INT(json, "your_turn"); //Set the AI's list of opponents SetGameOpponents(game, JSON(json, "players_at_table")); //Update the current pot game->current_pot = game->current_bet; for (int i = 0; i < game->num_opponents; i++) { game->current_pot += game->opponents[i].current_bet; } //Set the AI's hand and the community cards game->handsize = GetCardArray(game->hand, JSON(json, "hand")); game->communitysize = GetCardArray(game->community, JSON(json, "community_cards")); UpdateGameDeck(game); }
JSON JSON::as_array() const { switch (m_type) { case e_null: return JSON(e_array); case e_object: return m_object.as_array(); case e_array: return *this; default: { JSON ret = JSON(e_array); ret.push(*this); return ret; } } }
JSON JSON::as_object() const { switch (m_type) { case e_null: return JSON(e_object); case e_array: return m_array.as_object(); case e_object: return *this; default: { JSON ret = JSON(e_object); ret[UTF16(g_sScalarKey)] = (*this); return ret; } } }
JSON::Pos JSON::skipArray() const { //std::cerr << "skipArray()\t" << data() << std::endl; if (!isArray()) throw JSONException("JSON: expected ["); Pos pos = ptr_begin; ++pos; checkPos(pos); if (*pos == ']') return ++pos; while (1) { pos = JSON(pos, ptr_end, level + 1).skipElement(); checkPos(pos); switch (*pos) { case ',': ++pos; break; case ']': return ++pos; default: throw JSONException(std::string("JSON: expected one of ',]', got ") + *pos); } } }
// Arrays JSON JSON::getArray(const char *key) { if (!_json) { return JSON(); } json_t *jarray = json_object_get(_json, key); if (!jarray || !json_is_array(jarray)) { return JSON(); } return JSON(jarray); }
// Objects JSON JSON::getObject(const char *key) { if (!_json) { return JSON(); } json_t *jobject = json_object_get(_json, key); if (!jobject || !json_is_object(jobject)) { return JSON(); } return JSON(jobject); }
JSON JSON::stringToNumber(const UTF16& sString) { if (sString.length() == 0) return JSON(0); return StringToNumberConverter(sString.ptr()).parse(); }
JSON JSON::getArrayArray(int index) { if (!isArray()) { return JSON(); } json_t *object = json_array_get(_json, index); if (!object || !json_is_array(object)) { return JSON(); } return JSON(object); }
JSON::Pos JSON::skipObject() const { //std::cerr << "skipObject()\t" << data() << std::endl; if (!isObject()) throw JSONException("JSON: expected {"); Pos pos = ptr_begin; ++pos; checkPos(pos); if (*pos == '}') return ++pos; while (1) { pos = JSON(pos, ptr_end, level + 1).skipNameValuePair(); checkPos(pos); switch (*pos) { case ',': ++pos; break; case '}': return ++pos; default: throw JSONException(std::string("JSON: expected one of ',}', got ") + *pos); } } }
void fix() { DB(contests); DB(problems); JSON aux; contests.update([&](Database::Document& doc) { if (doc.second("judges").isarr()) { auto& a = doc.second["judges"].arr(); sort(a.begin(),a.end(),std::less<int>()); } auto& ps = doc.second["problems"]; if (!ps.isarr()) { ps = JSON(vector<JSON>{}); return true; } for (int id : ps.arr()) if (problems.retrieve(id,aux)) { aux["contest"] = doc.first; problems.update(id,move(aux)); } return true; }); problems.update([&](Database::Document& doc) { int cid; if ( !doc.second["contest"].read(cid) || !contests.retrieve(cid,aux)) { doc.second.erase("contest"); return true; } for (int id : aux["problems"].arr()) if (id == doc.first) return true; doc.second.erase("contest"); return true; }); }
JSON JSON::operator[] (const std::string & name) const { Pos pos = searchField(name); if (!pos) throw JSONException("JSON: there is no element '" + std::string(name) + "' in object."); return JSON(pos, ptr_end, level + 1).getValue(); }
void PollThread::parse(QByteArray json) { QVariantMap dataset = JSON(json.data()).getSerial().toMap(); emit count(dataset.value("count").toInt()); emit queuetimes(dataset.value("spyeeQueueTime").toDouble(), dataset.value("spyQueueTime").toDouble()); emit timestamp(dataset.value("timestamp").toDouble()); emit servers(dataset.value("servers").toStringList()); }
void SampleClient::onSocketOpen(std::string const& nsp){ //データ送受信のイベントはclientではなくsocket単位のため、ここで登録する。 std::cout<<"onSocketOpen("<<nsp<<")"<<std::endl; if(nsp=="/"){ client.socket(nsp)->on("server push",std::bind(&SampleClient::OnAnEvent,this,std::placeholders::_1)); client.socket()->emit("enter_room",JSON().add("room","Client").pack()); } }
JSON JSON::getValue() const { Pos pos = skipString(); checkPos(pos); if (*pos != ':') throw JSONException("JSON: expected :."); ++pos; checkPos(pos); return JSON(pos, ptr_end, level + 1); }
double JSON::toDouble() const { ElementType type = getType(); if (type == TYPE_NUMBER) return getDouble(); else if (type == TYPE_STRING) return JSON(ptr_begin + 1, ptr_end, level + 1).getDouble(); else throw JSONException("JSON: cannot convert value to double."); }
UInt64 JSON::toUInt() const { ElementType type = getType(); if (type == TYPE_NUMBER) return getUInt(); else if (type == TYPE_STRING) return JSON(ptr_begin + 1, ptr_end, level + 1).getUInt(); else throw JSONException("JSON: cannot convert value to unsigned integer."); }
JSON JSONObject::as_array() const { JSON result; TreeMap<UTF16, JSON>::Iterator it(m_core->m_tree); UTF16 sKey; JSON value; while (it(sKey, value)) { result.push(JSON(sKey)); result.push(value); } return result; }
JSON::Pos JSON::skipNameValuePair() const { //std::cerr << "skipNameValuePair()\t" << data() << std::endl; Pos pos = skipString(); checkPos(pos); if (*pos != ':') throw JSONException("JSON: expected :."); ++pos; return JSON(pos, ptr_end, level + 1).skipElement(); }
JSON* JSON::getObjectNew(const char *key) { if (!_json) { return NULL; } json_t *jobject = json_object_get(_json, key); if (!jobject || !json_is_object(jobject)) { return NULL; } return lmNew(NULL) JSON(jobject); }
JSON* JSON::getArrayNew(const char *key) { if (!_json) { return NULL; } json_t *jarray = json_object_get(_json, key); if (!jarray || !json_is_array(jarray)) { return NULL; } return lmNew(NULL) JSON(jarray); }
JSON* JSON::getArrayArrayNew(int index) { if (!isArray()) { return NULL; } json_t *object = json_array_get(_json, index); if (!object || !json_is_array(object)) { return NULL; } return lmNew(NULL) JSON(object); }
JSON::iterator JSON::iterator::begin() const { ElementType type = getType(); if (type != TYPE_ARRAY && type != TYPE_OBJECT) throw JSONException("JSON: not array or object when calling begin() method."); //std::cerr << "begin()\t" << data() << std::endl; Pos pos = ptr_begin + 1; checkPos(pos); if (*pos == '}' || *pos == ']') return end(); return JSON(pos, ptr_end, level + 1); }
void JSONObject::generate(Error& error, const HOutputStream& out) const { out->twrite(error, Chr8('{')); if (error) return; if (size() > 0) { bool bFirst = true; TreeMap<UTF16, JSON>::Iterator it(m_core->m_tree); UTF16 sKey; JSON value; while (it(sKey, value)) { if (bFirst) bFirst = false; else { out->twrite(error, UTF8(", ")); if (error) return; } JSON(sKey).generate(error, out); if (error) return; out->twrite(error, UTF8(": ")); if (error) return; value.generate(error, out); if (error) return; } } out->twrite(error, Chr8('}')); if (error) return; }
JSON scoreboard(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; JSON ans(map<string,JSON>{ {"status" , contest("finished") ? "final" : ""}, {"attempts" , JSON()}, {"colors" , vector<JSON>{}} }); // get problem info JSON probs = list_problems(contest,user); map<int,int> idx; for (auto& prob : probs.arr()) { idx[prob["id"]] = ans["colors"].size(); ans["colors"].push_back(prob["color"]); } // get attempts ans["attempts"] = Attempt::page(user,0,0,id,true); // set info auto& arr = ans["attempts"].arr(); for (auto& att : arr) { att["problem"] = idx[att["problem"]["id"]]; att["user"] = User::name(att["user"]); } // no freeze/blind filtering needed? if ( contest("finished") || (int(contest["freeze"]) == 0 && int(contest["blind"]) == 0) || isjudge(user,contest) ) return ans; // freeze/blind filtering int freeze = int(contest["duration"])-int(contest["freeze"]); int blind = int(contest["duration"])-int(contest["blind"]); freeze = min(freeze,blind); time_t frz = begin(contest) + 60*freeze; if (frz <= ::time(nullptr)) ans["status"] = "frozen"; ans["freeze"] = freeze; JSON tmp(vector<JSON>{}); for (auto& att : arr) if (int(att["contest_time"]) < freeze) { tmp.push_back(move(att)); } ans["attempts"] = move(tmp); return ans; }
JSON parse() { bool bPositive = (!tryParse(L'-')); if (bPositive) tryParse(L'+'); SInt64 iBase; UInt8 iFirstDigit; if (Character::decDigit(peek(), iFirstDigit) == Character::eCodingFailure) return JSON(1); iBase = iFirstDigit; pop(); if (iBase != 0) { UInt8 iNextDigit; while (Character::decDigit(peek(), iNextDigit) == Character::eCodingSuccess) { pop(); iBase *= 10; iBase += iNextDigit; } } Real64 fBase = Real64(iBase); bool bPoint = tryParse(L'.'); if (bPoint) { Real64 fFactor = 0.1; UInt8 iNextDigit; while (Character::decDigit(peek(), iNextDigit) == Character::eCodingSuccess) { pop(); fBase += (fFactor * iNextDigit); fFactor /= 10; } } bool bExponent = (tryParse(L'e') || tryParse(L'E')); if (bExponent) { bool bPositiveExponent = (!tryParse(L'-')); if (bPositiveExponent) tryParse(L'+'); SInt64 iExponent; UInt8 iFirstDigit; if (Character::decDigit(peek(), iFirstDigit) == Character::eCodingSuccess) { iExponent = iFirstDigit; pop(); UInt8 iNextDigit; while (Character::decDigit(peek(), iNextDigit) == Character::eCodingSuccess) { pop(); iExponent *= 10; iExponent += iNextDigit; } if (bPositiveExponent) fBase *= std::pow(Real64(10),Real64(iExponent)); else fBase *= std::pow(Real64(10),Real64(-iExponent)); } else bExponent = false; } if (bPoint || bExponent) { if (bPositive) return JSON(fBase); else return JSON(-fBase); } else { if (bPositive) return JSON(iBase); else return JSON(-iBase); } }
void JSON::setNull() { (*this) = JSON(); }
JSON::iterator JSON::iterator::end() const { return JSON(nullptr, ptr_end, level + 1); }
JSON JSON::at(size_t idx) const { return JSON(node->at(idx), allocator); }
JSON JSON::key(const char *key) const { return JSON(node->key(key), allocator); }