CardData* MtgJsonAllSetsData::createCardData( int multiverseId ) const { // Unfortunately this is a slow linear search. for( const std::string& setCode : mAllSetCodes ) { // In parse() this was vetted to be safe and yield an Array-type value. const Value& cardsValue = mDoc[setCode]["cards"]; // This is a linear search looking for the multiverse id. for( Value::ConstValueIterator iter = cardsValue.Begin(); iter != cardsValue.End(); ++iter ) { if( iter->HasMember("multiverseid") ) { const Value& multiverseIdValue = (*iter)["multiverseid"]; if( multiverseIdValue.IsInt() ) { int muid = multiverseIdValue.GetInt(); if( muid == multiverseId ) { mLogger->debug( "found muid ", muid ); return new MtgJsonCardData( setCode, *iter ); } } } } } mLogger->warn( "unable to find card multiverseId {}", multiverseId ); return nullptr; }
Value::ConstValueIterator MtgJsonAllSetsData::findCardValueByName( Value::ConstValueIterator first, Value::ConstValueIterator last, const std::string& name ) const { Value::ConstValueIterator iter = first; for( Value::ConstValueIterator iter = first; iter != last; ++iter ) { std::string nameStr( (*iter)["name"].GetString() ); if( StringUtil::icompare( nameStr, name ) ) { mLogger->debug( "found name {}", name ); return iter; } else if( iter->HasMember("names") ) { // Here we check if the card has multiple names, i.e. split // cards. If so, create a split card name and normalize the // name parameter and see if they match. std::string splitCardName = MtgJson::createSplitCardName( (*iter)["names"] ); std::string nameNormalized = MtgJson::normalizeSplitCardName( name ); if( StringUtil::icompare( nameNormalized, splitCardName ) ) { mLogger->debug( "found split name {}", name ); return iter; } } } return last; }
bool JSASTProgram::Parse(const rapidjson::Value& value) { JSASTNode::Parse(value); for (Value::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { String name = itr->name.GetString(); if (name == "body") { ParseStatementArray(itr->value, body_); } if (name == "comments") { if (itr->value.IsArray()) { for (Value::ConstValueIterator citr = itr->value.Begin(); citr != itr->value.End(); citr++) { JSASTComment* comment = new JSASTComment(); assert(citr->IsObject()); comment->Parse(*citr); comments_.Push(comment); } } } } return true; }
void AEPreferences::Read() { rapidjson::Document document; String filepath = GetPreferencesFullPath(); File jsonFile(context_, filepath); if (!jsonFile.IsOpen()) return; String json; jsonFile.ReadText(json); if (!json.Length()) return; if (document.Parse<0>(json.CString()).HasParseError()) { LOGERRORF("Could not parse JSON data from %s", filepath.CString()); return; } Clear(); const Value::Member* recent_files = document.FindMember("recent_files"); if (recent_files && recent_files->value.IsArray()) { for (Value::ConstValueIterator itr = recent_files->value.Begin(); itr != recent_files->value.End(); itr++) { if (!(*itr).IsString()) continue; String path(itr->GetString()); recentProjects_.Push(path.CString()); } } const Value::Member* android_sdk_path = document.FindMember("android_sdk_path"); if (android_sdk_path && android_sdk_path->value.IsString()) androidSDKPath_ = android_sdk_path->value.GetString(); const Value::Member* jdk_root_path = document.FindMember("jdk_root_path"); if (jdk_root_path && jdk_root_path->value.IsString()) jdkRootPath_ = jdk_root_path->value.GetString(); const Value::Member* ant_path = document.FindMember("ant_path"); if (ant_path && ant_path->value.IsString()) antPath_ = ant_path->value.GetString(); UpdateRecentFiles(false); }
/* * Class: com_vmc_ipc_proxy_IpcProxy * Method: takeNavDataSnapshot * Signature: ()Lcom/vmc/ipc/proxy/NavData; */ JNIEXPORT jobjectArray JNICALL Java_com_vmc_ipc_proxy_IpcProxy_takeNavDataSnapshot (JNIEnv *env, jobject jobj,jobject navdata){ // LOGI("-->Java_com_vmc_ipc_proxy_IpcProxy_takeNavDataSnapshot"); jobjectArray args = 0; jstring str; std::map<std::string,std::string> &map = cmd::StartServerStatusEnum(); int i = 0,len = map.size(); std::map<std::string,std::string>::iterator iter; args = (env)->NewObjectArray(len,(env)->FindClass("java/lang/String"),0); #if 0 for (Value::ConstValueIterator itr = g_serverStatus.Begin(); itr != g_serverStatus.End(); ++itr) { str = (env)->NewStringUTF(itr->GetString() ); (env)->SetObjectArrayElement(args, i, str); i++; } #endif for(iter = map.begin();iter != map.end(); iter++) { std::string s = iter->first; s += ":"; s += iter->second; str = (env)->NewStringUTF(s.c_str() ); (env)->SetObjectArrayElement(args, i, str); i++; } cmd::EndServerStatusEnum(); #if 0 for (rapidjson::Value::ConstMemberIterator itr = g_serverStatus.MemberBegin(); itr != g_serverStatus.MemberEnd(); ++itr) { std::string s = itr->name.GetString(); s += ","; s += itr->value.GetString(); (env)->SetObjectArrayElement(args, i, s.c_str()); i++; printf("Type of member %s is %s\n", itr->name.GetString(), itr->value.GetString()); } #endif #if 0 for( i=0; i < len; i++ ) { str = (env)->NewStringUTF(sa[i] ); (env)->SetObjectArrayElement(args, i, str); } #endif return args; }
//将支持api保存到mSupportedApiSet void Device::loadSupportedApiList(const Document &replyJson) { mSupportedApiSet.clear(); if (replyJson == NULL || replyJson.IsNull()) return; if (replyJson.HasMember("error")) { return; } Value::ConstArray a = replyJson["result"].GetArray()[0].GetArray(); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) { mSupportedApiSet.insert(itr->GetString()); } }
//设置曝光模式 void CLiveview::OnCbnSelchangeCombo3() { int nIndex = mExpoCombo.GetCurSel(); CString sel; mExpoCombo.GetLBText(nIndex, sel); Document d = indevice->setExposureMode(sel); if (indevice->isJsonOk(d)) { //获取支持的ISO mIsoCombo.ResetContent(); const Document replyJson3 = indevice->getAvailableIsoSpeedRate(); if (indevice->isJsonOk(replyJson3)) { CString curIso = replyJson3["result"].GetArray()[0].GetString(); Value::ConstArray a = replyJson3["result"].GetArray()[1].GetArray(); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) { mIsoCombo.AddString(itr->GetString()); } mIsoCombo.SelectString(0, curIso); } } }
void JSONArray::_parseRapidJSONArray(void *value) { rapidjson::Value *rapidjsonValue = (rapidjson::Value *)value; for (Value::ConstValueIterator currentValue = rapidjsonValue->Begin(); currentValue != rapidjsonValue->End(); ++currentValue) switch (currentValue->GetType()) { case kNullType: break; case kFalseType: case kTrueType: this->appendValue(shared_ptr<JSONNumber> (new JSONNumber(kTrueType ? true: false))); break; case kObjectType: { shared_ptr<JSONObject> obj(new JSONObject()); obj->_parseRapidJSONObject((void*)currentValue); this->appendValue(obj); } break; case kArrayType: { shared_ptr<JSONArray> obj(new JSONArray()); obj->_parseRapidJSONArray((void*)currentValue); this->appendValue(obj); } break; case kStringType: this->appendValue(shared_ptr<JSONString> (new JSONString(currentValue->GetString()))); break; case kNumberType: if (rapidjsonValue->IsDouble()) { this->appendValue(shared_ptr<JSONNumber> (new JSONNumber(currentValue->GetDouble()))); } else if (rapidjsonValue->IsInt() || currentValue->IsInt64()) { this->appendValue(shared_ptr<JSONNumber> (new JSONNumber(currentValue->GetInt()))); } else if (currentValue->IsUint() || currentValue->IsUint64()) { this->appendValue(shared_ptr<JSONNumber> (new JSONNumber(currentValue->GetUint()))); } break; } }
TEST(Value, Array) { Value x(kArrayType); const Value& y = x; Value::AllocatorType allocator; EXPECT_EQ(kArrayType, x.GetType()); EXPECT_TRUE(x.IsArray()); EXPECT_TRUE(x.Empty()); EXPECT_EQ(0u, x.Size()); EXPECT_TRUE(y.IsArray()); EXPECT_TRUE(y.Empty()); EXPECT_EQ(0u, y.Size()); EXPECT_FALSE(x.IsNull()); EXPECT_FALSE(x.IsBool()); EXPECT_FALSE(x.IsFalse()); EXPECT_FALSE(x.IsTrue()); EXPECT_FALSE(x.IsString()); EXPECT_FALSE(x.IsObject()); // PushBack() Value v; x.PushBack(v, allocator); v.SetBool(true); x.PushBack(v, allocator); v.SetBool(false); x.PushBack(v, allocator); v.SetInt(123); x.PushBack(v, allocator); EXPECT_FALSE(x.Empty()); EXPECT_EQ(4u, x.Size()); EXPECT_FALSE(y.Empty()); EXPECT_EQ(4u, y.Size()); EXPECT_TRUE(x[SizeType(0)].IsNull()); EXPECT_TRUE(x[1u].IsTrue()); EXPECT_TRUE(x[2u].IsFalse()); EXPECT_TRUE(x[3u].IsInt()); EXPECT_EQ(123, x[3u].GetInt()); EXPECT_TRUE(y[SizeType(0)].IsNull()); EXPECT_TRUE(y[1u].IsTrue()); EXPECT_TRUE(y[2u].IsFalse()); EXPECT_TRUE(y[3u].IsInt()); EXPECT_EQ(123, y[3u].GetInt()); // iterator Value::ValueIterator itr = x.Begin(); EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsNull()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsTrue()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsFalse()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsInt()); EXPECT_EQ(123, itr->GetInt()); // const iterator Value::ConstValueIterator citr = y.Begin(); EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsNull()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsTrue()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsFalse()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsInt()); EXPECT_EQ(123, citr->GetInt()); // PopBack() x.PopBack(); EXPECT_EQ(3u, x.Size()); EXPECT_TRUE(y[SizeType(0)].IsNull()); EXPECT_TRUE(y[1].IsTrue()); EXPECT_TRUE(y[2].IsFalse()); // Clear() x.Clear(); EXPECT_TRUE(x.Empty()); EXPECT_EQ(0u, x.Size()); EXPECT_TRUE(y.Empty()); EXPECT_EQ(0u, y.Size()); // SetArray() Value z; z.SetArray(); EXPECT_TRUE(z.IsArray()); EXPECT_TRUE(z.Empty()); }
int main(int, char*[]) { //////////////////////////////////////////////////////////////////////////// // 1. Parse a JSON text string to a document. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; printf("Original JSON:\n %s\n", json); Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. #if 0 // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream(). if (document.Parse(json).HasParseError()) return 1; #else // In-situ parsing, decode strings directly in the source string. Source must be string. char buffer[sizeof(json)]; memcpy(buffer, json, sizeof(json)); if (document.ParseInsitu(buffer).HasParseError()) return 1; #endif printf("\nParsing to document succeeded.\n"); //////////////////////////////////////////////////////////////////////////// // 2. Access values in document. printf("\nAccess values in document:\n"); assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. assert(document.HasMember("hello")); assert(document["hello"].IsString()); printf("hello = %s\n", document["hello"].GetString()); // Since version 0.2, you can use single lookup to check the existing of member and its value: Value::MemberIterator hello = document.FindMember("hello"); assert(hello != document.MemberEnd()); assert(hello->value.IsString()); assert(strcmp("world", hello->value.GetString()) == 0); (void)hello; assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue(). printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); assert(document["f"].IsBool()); printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type. assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true. printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] assert(document["pi"].IsNumber()); assert(document["pi"].IsDouble()); printf("pi = %g\n", document["pi"].GetDouble()); { const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster. assert(a.IsArray()); for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t. printf("a[%d] = %d\n", i, a[i].GetInt()); int y = a[0].GetInt(); (void)y; // Iterating array with iterators printf("a = "); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) printf("%d ", itr->GetInt()); printf("\n"); } // Iterating object members static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); //////////////////////////////////////////////////////////////////////////// // 3. Modify values in document. // Change i to a bigger number { uint64_t f20 = 1; // compute factorial of 20 for (uint64_t j = 1; j <= 20; j++) f20 *= j; document["i"] = f20; // Alternate form: document["i"].SetUint64(f20) assert(!document["i"].IsInt()); // No longer can be cast as int or uint. } // Adding values to array. { Value& a = document["a"]; // This time we uses non-const reference. Document::AllocatorType& allocator = document.GetAllocator(); for (int i = 5; i <= 10; i++) a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. // Fluent API a.PushBack("Lua", allocator).PushBack("Mio", allocator); } // Making string values. // This version of SetString() just store the pointer to the string. // So it is for literal and string that exists within value's life-cycle. { document["hello"] = "rapidjson"; // This will invoke strlen() // Faster version: // document["hello"].SetString("rapidjson", 9); } // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer. Value author; { char buffer[10]; int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator()); // Shorter but slower version: // document["hello"].SetString(buffer, document.GetAllocator()); // Constructor version: // Value author(buffer, len, document.GetAllocator()); // Value author(buffer, document.GetAllocator()); memset(buffer, 0, sizeof(buffer)); // For demonstration purpose. } // Variable 'buffer' is unusable now but 'author' has already made a copy. document.AddMember("author", author, document.GetAllocator()); assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. //////////////////////////////////////////////////////////////////////////// // 4. Stringify JSON printf("\nModified JSON with reformatting:\n"); StringBuffer sb; PrettyWriter<StringBuffer> writer(sb); document.Accept(writer); // Accept() traverses the DOM and generates Handler events. puts(sb.GetString()); return 0; }
/* **************************************************************************** * * parseContextAttributeCompoundValueStandAlone - */ std::string parseContextAttributeCompoundValueStandAlone ( Document& document, ContextAttribute* caP, orion::ValueType valueType ) { caP->compoundValueP = new orion::CompoundValueNode(); caP->compoundValueP->name = "TOP"; caP->compoundValueP->container = caP->compoundValueP; caP->compoundValueP->valueType = caP->valueType; // Convert to other type? caP->compoundValueP->path = "/"; caP->compoundValueP->rootP = caP->compoundValueP; caP->compoundValueP->level = 0; caP->compoundValueP->siblingNo = 0; orion::CompoundValueNode* parent = caP->compoundValueP; // // Children of the node // if (caP->valueType == orion::ValueTypeVector) { int counter = 0; for (Value::ConstValueIterator iter = document.Begin(); iter != document.End(); ++iter) { std::string nodeType = jsonParseTypeNames[iter->GetType()]; orion::CompoundValueNode* cvnP = new orion::CompoundValueNode(); char itemNo[4]; snprintf(itemNo, sizeof(itemNo), "%03d", counter); cvnP->valueType = stringToCompoundType(nodeType); cvnP->container = parent; cvnP->rootP = parent->rootP; cvnP->level = parent->level + 1; cvnP->siblingNo = counter; cvnP->path = parent->path + "[" + itemNo + "]"; if (nodeType == "String") { cvnP->stringValue = iter->GetString(); } else if (nodeType == "Number") { cvnP->numberValue = iter->GetDouble(); } else if ((nodeType == "True") || (nodeType == "False")) { cvnP->boolValue = (nodeType == "True")? true : false; } else if (nodeType == "Null") { cvnP->valueType = orion::ValueTypeNone; } else if (nodeType == "Object") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeObject; } else if (nodeType == "Array") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeVector; } parent->childV.push_back(cvnP); // // Start recursive calls if Object or Array // if ((nodeType == "Object") || (nodeType == "Array")) { parseContextAttributeCompoundValue(iter, caP, cvnP); } else if (!caP->typeGiven) { caP->type = defaultType(caP->valueType); } ++counter; } } else if (caP->valueType == orion::ValueTypeObject) { int counter = 0; for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter) { std::string nodeType = jsonParseTypeNames[iter->value.GetType()]; orion::CompoundValueNode* cvnP = new orion::CompoundValueNode(); cvnP->name = iter->name.GetString(); cvnP->valueType = stringToCompoundType(nodeType); cvnP->container = parent; cvnP->rootP = parent->rootP; cvnP->level = parent->level + 1; cvnP->siblingNo = counter; cvnP->path = parent->path + cvnP->name; if (nodeType == "String") { cvnP->stringValue = iter->value.GetString(); } else if (nodeType == "Number") { cvnP->numberValue = iter->value.GetDouble(); } else if ((nodeType == "True") || (nodeType == "False")) { cvnP->boolValue = (nodeType == "True")? true : false; } else if (nodeType == "Null") { cvnP->valueType = orion::ValueTypeNone; } else if (nodeType == "Object") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeObject; } else if (nodeType == "Array") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeVector; } parent->childV.push_back(cvnP); // // Start recursive calls if Object or Array // if ((nodeType == "Object") || (nodeType == "Array")) { parseContextAttributeCompoundValue(iter, caP, cvnP); } else if (!caP->typeGiven) { caP->type = defaultType(caP->valueType); } ++counter; } } return "OK"; }
/* **************************************************************************** * * parseContextAttributeCompoundValue - */ std::string parseContextAttributeCompoundValue ( const Value::ConstValueIterator& node, ContextAttribute* caP, orion::CompoundValueNode* parent ) { if (node->IsObject()) { int counter = 0; for (Value::ConstMemberIterator iter = node->MemberBegin(); iter != node->MemberEnd(); ++iter) { std::string nodeType = jsonParseTypeNames[iter->value.GetType()]; orion::CompoundValueNode* cvnP = new orion::CompoundValueNode(); cvnP->valueType = stringToCompoundType(nodeType); cvnP->name = iter->name.GetString(); cvnP->container = parent; cvnP->rootP = parent->rootP; cvnP->level = parent->level + 1; cvnP->siblingNo = counter; cvnP->path = parent->path + cvnP->name; if (nodeType == "String") { cvnP->stringValue = iter->value.GetString(); } else if (nodeType == "Number") { cvnP->numberValue = iter->value.GetDouble(); } else if ((nodeType == "True") || (nodeType == "False")) { cvnP->boolValue = (nodeType == "True")? true : false; } else if (nodeType == "Null") { cvnP->valueType = orion::ValueTypeNone; } else if (nodeType == "Object") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeObject; } else if (nodeType == "Array") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeVector; } parent->childV.push_back(cvnP); // // Recursive call if Object or Array // if ((nodeType == "Object") || (nodeType == "Array")) { parseContextAttributeCompoundValue(iter, caP, cvnP); } ++counter; } } else if (node->IsArray()) { int counter = 0; for (Value::ConstValueIterator iter = node->Begin(); iter != node->End(); ++iter) { std::string nodeType = jsonParseTypeNames[iter->GetType()]; orion::CompoundValueNode* cvnP = new orion::CompoundValueNode(); char itemNo[4]; snprintf(itemNo, sizeof(itemNo), "%03d", counter); cvnP->valueType = stringToCompoundType(nodeType); cvnP->container = parent; cvnP->rootP = parent->rootP; cvnP->level = parent->level + 1; cvnP->siblingNo = counter; cvnP->path = parent->path + "[" + itemNo + "]"; if (nodeType == "String") { cvnP->stringValue = iter->GetString(); } else if (nodeType == "Number") { cvnP->numberValue = iter->GetDouble(); } else if ((nodeType == "True") || (nodeType == "False")) { cvnP->boolValue = (nodeType == "True")? true : false; } else if (nodeType == "Null") { cvnP->valueType = orion::ValueTypeNone; } else if (nodeType == "Object") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeObject; } else if (nodeType == "Array") { cvnP->path += "/"; cvnP->valueType = orion::ValueTypeVector; } parent->childV.push_back(cvnP); // // Recursive call if Object or Array // if ((nodeType == "Object") || (nodeType == "Array")) { parseContextAttributeCompoundValue(iter, caP, cvnP); } ++counter; } } return "OK"; }
TEST(Value, Array) { Value x(kArrayType); const Value& y = x; Value::AllocatorType allocator; EXPECT_EQ(kArrayType, x.GetType()); EXPECT_TRUE(x.IsArray()); EXPECT_TRUE(x.Empty()); EXPECT_EQ(0u, x.Size()); EXPECT_TRUE(y.IsArray()); EXPECT_TRUE(y.Empty()); EXPECT_EQ(0u, y.Size()); EXPECT_FALSE(x.IsNull()); EXPECT_FALSE(x.IsBool()); EXPECT_FALSE(x.IsFalse()); EXPECT_FALSE(x.IsTrue()); EXPECT_FALSE(x.IsString()); EXPECT_FALSE(x.IsObject()); // PushBack() Value v; x.PushBack(v, allocator); v.SetBool(true); x.PushBack(v, allocator); v.SetBool(false); x.PushBack(v, allocator); v.SetInt(123); x.PushBack(v, allocator); //x.PushBack((const char*)"foo", allocator); // should not compile x.PushBack("foo", allocator); EXPECT_FALSE(x.Empty()); EXPECT_EQ(5u, x.Size()); EXPECT_FALSE(y.Empty()); EXPECT_EQ(5u, y.Size()); EXPECT_TRUE(x[SizeType(0)].IsNull()); EXPECT_TRUE(x[1].IsTrue()); EXPECT_TRUE(x[2].IsFalse()); EXPECT_TRUE(x[3].IsInt()); EXPECT_EQ(123, x[3].GetInt()); EXPECT_TRUE(y[SizeType(0)].IsNull()); EXPECT_TRUE(y[1].IsTrue()); EXPECT_TRUE(y[2].IsFalse()); EXPECT_TRUE(y[3].IsInt()); EXPECT_EQ(123, y[3].GetInt()); EXPECT_TRUE(y[4].IsString()); EXPECT_STREQ("foo", y[4].GetString()); #if RAPIDJSON_HAS_CXX11_RVALUE_REFS // PushBack(GenericValue&&, Allocator&); { Value y(kArrayType); y.PushBack(Value(true), allocator); y.PushBack(std::move(Value(kArrayType).PushBack(Value(1), allocator).PushBack("foo", allocator)), allocator); EXPECT_EQ(2u, y.Size()); EXPECT_TRUE(y[0].IsTrue()); EXPECT_TRUE(y[1].IsArray()); EXPECT_EQ(2u, y[1].Size()); EXPECT_TRUE(y[1][0].IsInt()); EXPECT_TRUE(y[1][1].IsString()); } #endif // iterator Value::ValueIterator itr = x.Begin(); EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsNull()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsTrue()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsFalse()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsInt()); EXPECT_EQ(123, itr->GetInt()); ++itr; EXPECT_TRUE(itr != x.End()); EXPECT_TRUE(itr->IsString()); EXPECT_STREQ("foo", itr->GetString()); // const iterator Value::ConstValueIterator citr = y.Begin(); EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsNull()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsTrue()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsFalse()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsInt()); EXPECT_EQ(123, citr->GetInt()); ++citr; EXPECT_TRUE(citr != y.End()); EXPECT_TRUE(citr->IsString()); EXPECT_STREQ("foo", citr->GetString()); // PopBack() x.PopBack(); EXPECT_EQ(4u, x.Size()); EXPECT_TRUE(y[SizeType(0)].IsNull()); EXPECT_TRUE(y[1].IsTrue()); EXPECT_TRUE(y[2].IsFalse()); EXPECT_TRUE(y[3].IsInt()); // Clear() x.Clear(); EXPECT_TRUE(x.Empty()); EXPECT_EQ(0u, x.Size()); EXPECT_TRUE(y.Empty()); EXPECT_EQ(0u, y.Size()); // Erase(ValueIterator) // Use array of array to ensure removed elements' destructor is called. // [[0],[1],[2],...] for (int i = 0; i < 10; i++) x.PushBack(Value(kArrayType).PushBack(i, allocator).Move(), allocator); // Erase the first itr = x.Erase(x.Begin()); EXPECT_EQ(x.Begin(), itr); EXPECT_EQ(9u, x.Size()); for (int i = 0; i < 9; i++) EXPECT_EQ(i + 1, x[static_cast<SizeType>(i)][0].GetInt()); // Ease the last itr = x.Erase(x.End() - 1); EXPECT_EQ(x.End(), itr); EXPECT_EQ(8u, x.Size()); for (int i = 0; i < 8; i++) EXPECT_EQ(i + 1, x[static_cast<SizeType>(i)][0].GetInt()); // Erase the middle itr = x.Erase(x.Begin() + 4); EXPECT_EQ(x.Begin() + 4, itr); EXPECT_EQ(7u, x.Size()); for (int i = 0; i < 4; i++) EXPECT_EQ(i + 1, x[static_cast<SizeType>(i)][0].GetInt()); for (int i = 4; i < 7; i++) EXPECT_EQ(i + 2, x[static_cast<SizeType>(i)][0].GetInt()); // Erase(ValueIterator, ValueIterator) // Exhaustive test with all 0 <= first < n, first <= last <= n cases const unsigned n = 10; for (unsigned first = 0; first < n; first++) { for (unsigned last = first; last <= n; last++) { x.Clear(); for (unsigned i = 0; i < n; i++) x.PushBack(Value(kArrayType).PushBack(i, allocator).Move(), allocator); itr = x.Erase(x.Begin() + first, x.Begin() + last); if (last == n) EXPECT_EQ(x.End(), itr); else EXPECT_EQ(x.Begin() + first, itr); size_t removeCount = last - first; EXPECT_EQ(n - removeCount, x.Size()); for (unsigned i = 0; i < first; i++) EXPECT_EQ(i, x[i][0].GetUint()); for (unsigned i = first; i < n - removeCount; i++) EXPECT_EQ(i + removeCount, x[static_cast<SizeType>(i)][0].GetUint()); } } // Working in gcc without C++11, but VS2013 cannot compile. To be diagnosed. // http://en.wikipedia.org/wiki/Erase-remove_idiom x.Clear(); for (int i = 0; i < 10; i++) if (i % 2 == 0) x.PushBack(i, allocator); else x.PushBack(Value(kNullType).Move(), allocator); const Value null(kNullType); x.Erase(std::remove(x.Begin(), x.End(), null), x.End()); EXPECT_EQ(5u, x.Size()); for (int i = 0; i < 5; i++) EXPECT_EQ(i * 2, x[static_cast<SizeType>(i)]); // SetArray() Value z; z.SetArray(); EXPECT_TRUE(z.IsArray()); EXPECT_TRUE(z.Empty()); }
bool PlayFabRequestHandler::DecodeRequest(int httpStatus, HttpRequest* request, void* userData, PlayFabBaseModel& outResult, PlayFabError& outError) { std::string response = request->GetReponse(); Document rawResult; rawResult.Parse<0>(response.c_str()); // Check for bad responses if (response.length() == 0 // Null response || rawResult.GetParseError() != NULL) // Non-Json response { // If we get here, we failed to connect meaningfully to the server - Assume a timeout outError.HttpCode = 408; outError.ErrorCode = PlayFabErrorConnectionTimeout; // For text returns, use the non-json response if possible, else default to no response outError.ErrorName = outError.ErrorMessage = outError.HttpStatus = response.length() == 0 ? "Request Timeout or null response" : response; return false; } // Check if the returned json indicates an error const Value::Member* errorCodeJson = rawResult.FindMember("errorCode"); if (errorCodeJson != NULL) { // There was an error, BUMMER if (!errorCodeJson->value.IsNumber()) { // unexpected json formatting - If we get here, we failed to connect meaningfully to the server - Assume a timeout outError.HttpCode = 408; outError.ErrorCode = PlayFabErrorConnectionTimeout; // For text returns, use the non-json response if possible, else default to no response outError.ErrorName = outError.ErrorMessage = outError.HttpStatus = response.length() == 0 ? "Request Timeout or null response" : response; return false; } // TODO: what happens when the error is not in the enum? outError.ErrorCode = static_cast<PlayFabErrorCode>(errorCodeJson->value.GetInt()); const Value::Member* codeJson = rawResult.FindMember("code"); if (codeJson != NULL && codeJson->value.IsNumber()) outError.HttpCode = codeJson->value.GetInt(); const Value::Member* statusJson = rawResult.FindMember("status"); if (statusJson != NULL && statusJson->value.IsString()) outError.HttpStatus = statusJson->value.GetString(); const Value::Member* errorNameJson = rawResult.FindMember("error"); if (errorNameJson != NULL && errorNameJson->value.IsString()) outError.ErrorName = errorNameJson->value.GetString(); const Value::Member* errorMessageJson = rawResult.FindMember("errorMessage"); if (errorMessageJson != NULL && errorMessageJson->value.IsString()) outError.ErrorMessage = errorMessageJson->value.GetString(); const Value::Member* errorDetailsJson = rawResult.FindMember("errorDetails"); if (errorDetailsJson != NULL && errorDetailsJson->value.IsObject()) { const Value& errorDetailsObj = errorDetailsJson->value; for (Value::ConstMemberIterator itr = errorDetailsObj.MemberBegin(); itr != errorDetailsObj.MemberEnd(); ++itr) { if (itr->name.IsString() && itr->value.IsArray()) { const Value& errorList = itr->value; for (Value::ConstValueIterator erroListIter = errorList.Begin(); erroListIter != errorList.End(); ++erroListIter) outError.ErrorDetails.insert(std::pair<std::string, std::string>(itr->name.GetString(), erroListIter->GetString())); } } } // We encountered no errors parsing the error return false; } const Value::Member* data = rawResult.FindMember("data"); if (data == NULL || !data->value.IsObject()) return false; return outResult.readFromValue(data->value); }
list loadCOCO( const std::string & name, int fold ) { using namespace rapidjson; // Load the annotations char buf[1024]; sprintf( buf, COCO_ANNOT.c_str(), name.c_str() ); // Read the json file Document doc; std::ifstream t(buf); std::string json_str = std::string(std::istreambuf_iterator<char>(t),std::istreambuf_iterator<char>()); doc.Parse( (char*)json_str.c_str() ); // Go through all instance labels std::unordered_map< uint64_t, std::vector<int> > categories; std::unordered_map< uint64_t, std::vector<float> > areas; std::unordered_map< uint64_t, std::vector<Polygons> > segments; const Value & instances = doc["instances"]; for ( Value::ConstValueIterator i = instances.Begin(); i != instances.End(); i++ ) { // Get the image id Value::ConstMemberIterator cmi_image_id = i->FindMember("image_id"); eassert( cmi_image_id != i->MemberEnd() ); const int image_id = cmi_image_id->value.GetInt(); // Get the category id Value::ConstMemberIterator cmi_category_id = i->FindMember("category_id"); eassert( cmi_category_id != i->MemberEnd() ); const int category_id = cmi_category_id->value.GetInt(); // Get the category id Value::ConstMemberIterator cmi_area = i->FindMember("area"); eassert( cmi_area != i->MemberEnd() ); const float area = cmi_area->value.GetDouble(); // Read the polygon Value::ConstMemberIterator cmi_segmentation = i->FindMember("segmentation"); eassert( cmi_segmentation != i->MemberEnd() ); const Value & segmentations = cmi_segmentation->value; // For now just use the first segmentation for each object Polygons polygons; for( Value::ConstValueIterator segmentation = segmentations.Begin(); segmentation!=segmentations.End(); segmentation++ ){ Polygon polygon = RMatrixXf( segmentation->Size() / 2, 2 ); float * ppolygon = polygon.data(); for ( Value::ConstValueIterator j = segmentation->Begin(); j != segmentation->End(); j++ ) *(ppolygon++) = j->GetDouble(); polygons.push_back( polygon ); } if( !ONLY_CONNECTED || polygons.size() == 1 ) { categories[ image_id ].push_back( category_id ); segments[ image_id ].push_back( polygons ); areas[ image_id ].push_back( area ); } } // Load all images Value::ConstValueIterator B = doc["images"].Begin(), E = doc["images"].End(); const int N = E-B; Value::ConstValueIterator i0 = B+(fold*N/N_FOLDS), i1 = B+((fold+1)*N/N_FOLDS); std::vector< std::shared_ptr<Image8u> > images( i1 - i0 ); #pragma omp parallel for for ( int k=0; k<i1-i0; k++ ) { Value::ConstValueIterator i = i0+k; // Get the file name and path Value::ConstMemberIterator cmi_file_name = i->FindMember("file_name"); eassert( cmi_file_name != i->MemberEnd() ); const std::string file_name = cmi_file_name->value.GetString(); Value::ConstMemberIterator cmi_file_path = i->FindMember("file_path"); eassert( cmi_file_path != i->MemberEnd() ); const std::string file_path = cmi_file_path->value.GetString(); // Add the image entry images[i-i0] = imreadShared( coco_dir+"/"+file_path+"/"+file_name ); } // Create the python struct with the result list r; for ( Value::ConstValueIterator i = i0; i != i1; i++ ) { // Get the image id Value::ConstMemberIterator cmi_image_id = i->FindMember("id"); eassert( cmi_image_id != i->MemberEnd() ); const int image_id = cmi_image_id->value.GetInt(); // Add the image entry const int N = categories[ image_id ].size(); if( N > 0 ){ dict entry; entry["id"] = image_id; entry["image"] = images[i - i0]; entry["categories"] = categories[ image_id ]; entry["areas"] = areas[ image_id ]; entry["segmentation"] = segments[ image_id ]; r.append( entry ); } // else // printf("Image '%d' doesn't have any annotations!\n", image_id ); } return r; }
void CLiveview::start() { Document replyJson; //如果支持startRecMode if (indevice->isCameraApiAvailable("startRecMode")) { replyJson = indevice->startRecMode(); //重新获取可用API replyJson = indevice->getAvailableApiList(); indevice->loadAvailableCameraApiList(replyJson); } //开始liveview 开两个子线程 一个获取图片 一个画出来 if (indevice->isCameraApiAvailable("startLiveview")) { CreateThread(0, 0, retrieveJPG, this, 0, 0); CreateThread(0, 0, drawJPEG, this, 0, 0); } //获取支持的拍摄模式 mComMod.ResetContent(); const Document replyJson2 = indevice->getAvailableShootMode(); if (indevice->isJsonOk(replyJson2)) { indevice->curShootMode = replyJson2["result"].GetArray()[0].GetString(); indevice->recording = false; Value::ConstArray a = replyJson2["result"].GetArray()[1].GetArray(); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) { indevice->mAvailableShootMod.push_back(itr->GetString()); mComMod.AddString(itr->GetString()); } mComMod.SelectString(0, indevice->curShootMode); } //获取支持的ISO mIsoCombo.ResetContent(); const Document replyJson3 = indevice->getAvailableIsoSpeedRate(); if (indevice->isJsonOk(replyJson3)) { CString curIso = replyJson3["result"].GetArray()[0].GetString(); Value::ConstArray a = replyJson3["result"].GetArray()[1].GetArray(); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) { mIsoCombo.AddString(itr->GetString()); } mIsoCombo.SelectString(0, curIso); } //获取支持的曝光模式 mExpoCombo.ResetContent(); const Document replyJson4 = indevice->getAvailableExposureMode(); if (indevice->isJsonOk(replyJson4)) { CString curExpo = replyJson4["result"].GetArray()[0].GetString(); Value::ConstArray a = replyJson4["result"].GetArray()[1].GetArray(); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) { mExpoCombo.AddString(itr->GetString()); } mExpoCombo.SelectString(0, curExpo); } indevice->getAvailableStillSize(); indevice->setStillSize(); indevice->setPostviewImageSize(); //获取是否支持调节焦距 if (!indevice->isCameraApiAvailable("actZoom")) { mBtnZoomIn.EnableWindow(0); mBtnZoomOut.EnableWindow(0); } FreshUI(); }
void iterateArray(Value::ConstValueIterator& itr, Value::ConstValueIterator& itrEnd, StringBuffer *buffer, Writer<StringBuffer> *writer, stringstream& ss) { for (; itr != itrEnd; itr++) { if (itr->IsObject()) { Value::ConstMemberIterator itr_ = itr->MemberBegin(); Value::ConstMemberIterator itrEnd_ = itr->MemberEnd(); iterateObject(itr_, itrEnd_, buffer, writer, ss); } else if (itr->IsArray()) { Value::ConstValueIterator itr_ = itr->Begin(); Value::ConstValueIterator itrEnd_ = itr->End(); iterateArray(itr_, itrEnd_, buffer, writer, ss); } else if (itr->IsBool()) { ss << DELIM << itr->GetBool(); } else if (itr->IsInt()) { ss << DELIM << itr->GetInt(); } else if (itr->IsInt64()) { ss << DELIM << itr->GetInt64(); } else if (itr->IsDouble()) { ss << DELIM << itr->GetDouble(); } else if (itr->IsString()) { ss << DELIM << "\"" << itr->GetString() << "\""; } else { throw runtime_error(string("Case missing from tokenizer")); } } }
std::vector<SlotType> MtgJsonAllSetsData::getBoosterSlots( const std::string& code ) const { std::vector<SlotType> boosterSlots; if( mBoosterSetCodes.count(code) == 0 ) { mLogger->warn( "No booster member in set {}, returning empty booster slots", code ); return boosterSlots; } // In parse() this was vetted to be safe and yield an Array-type value. const Value& boosterValue = mDoc[code]["booster"]; mLogger->debug( "{:-^40}", "assembling booster slots" ); for( Value::ConstValueIterator iter = boosterValue.Begin(); iter != boosterValue.End(); ++iter ) { if( iter->IsArray() ) { // create a set of any strings in the array std::set<std::string> slotArraySet; for( unsigned i = 0; i < iter->Size(); ++i ) { const Value& val = (*iter)[i]; if( val.IsString() ) { slotArraySet.insert( val.GetString() ); mLogger->debug( "booster slot array[{}]: {}", i, val.GetString() ); } else { mLogger->warn( "Non-string in booster slot array, ignoring!" ); } } const std::set<std::string> rareMythicRareSlot { "rare", "mythic rare" }; if( slotArraySet == rareMythicRareSlot ) boosterSlots.push_back( SLOT_RARE_OR_MYTHIC_RARE ); else mLogger->warn( "Unrecognized booster slot array, ignoring!" ); } else if( iter->IsString() ) { std::string slotStr( iter->GetString() ); mLogger->debug( "booster slot string: {}", slotStr ); if( slotStr == "common" ) boosterSlots.push_back( SLOT_COMMON ); else if( slotStr == "uncommon" ) boosterSlots.push_back( SLOT_UNCOMMON ); else if( slotStr == "rare" ) boosterSlots.push_back( SLOT_RARE ); else if( slotStr == "timeshifted purple" ) boosterSlots.push_back( SLOT_TIMESHIFTED_PURPLE ); else if( slotStr == "land" ) { /* do nothing */ } else if( slotStr == "marketing" ) { /* do nothing */ } else mLogger->warn( "Unrecognized booster slot type {}, ignoring!", slotStr ); } else { mLogger->warn( "Non-string booster slot type, ignoring!" ); } } return boosterSlots; }
std::multimap<RarityType,std::string> MtgJsonAllSetsData::getCardPool( const std::string& code ) const { std::multimap<RarityType,std::string> rarityMap; if( mAllSetCodes.count(code) == 0 ) { mLogger->warn( "Unable to find set {}, returning empty card pool", code ); return rarityMap; } // In parse() this was vetted to be safe and yield an Array-type value. const Value& cardsValue = mDoc[code]["cards"]; mLogger->debug( "{:-^40}", "assembling card pool" ); for( Value::ConstValueIterator iter = cardsValue.Begin(); iter != cardsValue.End(); ++iter ) { Value::ConstMemberIterator nameIter = iter->FindMember( "name" ); Value::ConstMemberIterator rarityIter = iter->FindMember( "rarity" ); if( nameIter != iter->MemberEnd() && nameIter->value.IsString() && rarityIter != iter->MemberEnd() && rarityIter->value.IsString() ) { std::string nameStr( nameIter->value.GetString() ); std::string rarityStr( rarityIter->value.GetString() ); mLogger->debug( "json: {} : {}", nameStr, rarityStr ); // Some cards have multiple entries (i.e. split/flip/double-sided), // so make sure they are only represented once. Done by skipping // over cards whose name doesn't match the first entry of the // 'names' array (if it exists). if( iter->HasMember("names") ) { const Value& names = (*iter)["names"]; if( names.IsArray() && !names.Empty() && (nameStr != names[0]) ) { continue; } // Modify the name for split cards. if( MtgJson::isSplitCard( *iter ) ) { nameStr = MtgJson::createSplitCardName( names ); } } // Some cards have variations with multiple entries that should // only be counted once. Done by checking if there are // variations and checking a card's number for a non-digit, // non-'a' ending. if( iter->HasMember("variations") && iter->HasMember("number") ) { const Value& numberValue = (*iter)["number"]; if( numberValue.IsString() ) { const std::string numberStr( numberValue.GetString() ); const char c = numberStr.back(); if( !std::isdigit( c ) && (c != 'a') ) { continue; } } } RarityType rarity = MtgJson::getRarityFromString( rarityStr ); if( rarity != RARITY_UNKNOWN ) rarityMap.insert( std::make_pair( rarity, nameStr ) ); else mLogger->warn( "Unknown rarity type {}, ignoring!", rarityStr ); } else { mLogger->notice( "card entry without name or rarity in set {}", code ); } } return rarityMap; }