TYPED_TEST(DocumentMove, MoveAssignmentParseError) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> Document; ParseResult noError; Document a; a.Parse("{ 4 = 4]"); ParseResult error(a.GetParseError(), a.GetErrorOffset()); EXPECT_TRUE(a.HasParseError()); EXPECT_NE(error.Code(), noError.Code()); EXPECT_NE(error.Offset(), noError.Offset()); Document b; b = std::move(a); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(b.HasParseError()); EXPECT_EQ(a.GetParseError(), noError.Code()); EXPECT_EQ(b.GetParseError(), error.Code()); EXPECT_EQ(a.GetErrorOffset(), noError.Offset()); EXPECT_EQ(b.GetErrorOffset(), error.Offset()); Document c; c = std::move(b); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(c.HasParseError()); EXPECT_EQ(b.GetParseError(), noError.Code()); EXPECT_EQ(c.GetParseError(), error.Code()); EXPECT_EQ(b.GetErrorOffset(), noError.Offset()); EXPECT_EQ(c.GetErrorOffset(), error.Offset()); }
/** Attempts to decode JSON from the given data./ (Try cut end of given json) \param [in] json The JSON. \param [out] outJson The out JSON. \param [out] outRest The out rest. \return true if it succeeds, false if it fails. */ bool XJson::tryDecode(const std::string &json) { // init output value outRest = ""; string jsonText = json; vector<string> rests; Document doc; string text, rest; size_t foundPosition; // try find valid part of json do { foundPosition = jsonText.rfind('}'); if (foundPosition == string::npos) { text = jsonText; jsonText = ""; } else { text = jsonText.substr(0, foundPosition + 1); rest = jsonText.substr(foundPosition + 1, jsonText.length()); trimRestJson(rest); if (rest != "") { rests.push_back(rest); jsonText = text; } else { jsonText = ""; } } text = "[" + text + "]"; doc.Parse<0>(text.c_str()); } while (doc.HasParseError() && jsonText != ""); // try it while not succeed // validate result if (doc.HasParseError()) { return false; } // create out rest stringstream ssRest; for (vector<string>::const_iterator it = rests.cend(); it != rests.cbegin(); --it) { ssRest << *it; } outRest = ssRest.str(); // create out json UrbiHandler handler; doc.Accept(handler); outJson = handler.getResult(); return true; }
static void* pfwl_field_tags_load_L7(pfwl_field_id_t field, const char* fileName){ void* db = NULL; if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_STRING){ db = new pfwl_field_matching_db_t; }else if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_MMAP){ db = new std::map<std::string, pfwl_field_matching_db_t>; } if(fileName){ std::ifstream ifs(fileName); IStreamWrapper isw(ifs); Document d; d.ParseStream(isw); if (d.HasParseError()){ return NULL; } const Value& rules = d["rules"]; assert(rules.IsArray()); for (Value::ConstValueIterator itr = rules.Begin(); itr != rules.End(); ++itr) { const Value& stringToMatch = (*itr)["value"]; const Value& matchingType = (*itr)["matchingType"]; const Value& tag = (*itr)["tag"]; if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_STRING){ pfwl_field_string_tags_add_internal(static_cast<pfwl_field_matching_db_t*>(db), stringToMatch.GetString(), getFieldMatchingType(matchingType.GetString()), tag.GetString()); }else if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_MMAP){ const Value& key = (*itr)["key"]; pfwl_field_mmap_tags_add_internal(static_cast<std::map<std::string, pfwl_field_matching_db_t>*>(db), key.GetString(), stringToMatch.GetString(), getFieldMatchingType(matchingType.GetString()), tag.GetString()); } } } return db; }
void ParseGameTitlesFromFile(std::map<GameID, std::string>& GameTitlesListOut) { SetCurrentDirectory(NativeStr(g_sHomeDir).c_str()); FILE* pf = nullptr; fopen_s(&pf, RA_TITLES_FILENAME, "rb"); if (pf != nullptr) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response")) { const Value& List = doc["Response"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { if (iter->name.IsNull() || iter->value.IsNull()) continue; GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10)); // KEYS ARE STRINGS, must convert afterwards! const std::string sTitle = iter->value.GetString(); GameTitlesListOut[nID] = sTitle; } } fclose(pf); } }
void LoginScene::onLoginResponse(HttpClient * sender, HttpResponse *response) { if (!response) return; if (!response->isSucceed()) { log("response failed"); log("error buffer: %s", response->getErrorBuffer()); return; } string res = Global::toString(response->getResponseData()); Document d; d.Parse<0>(res.c_str()); if (d.HasParseError()) { CCLOG("GetParseError %s\n", d.GetParseError()); } if (d.IsObject() && d.HasMember("result") && d.HasMember("info")) { bool result = d["result"].GetBool(); if (result) { Global::saveStatus(response->getResponseHeader(), textField->getString()); Director::getInstance()->replaceScene(TransitionFade::create(1, GameScene::createScene())); } else { CCLOG("Failed to login: %s\n", d["info"].GetString()); } } }
TYPED_TEST(DocumentMove, MoveAssignment) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> Document; Allocator allocator; Document a(&allocator); a.Parse("[\"one\", \"two\", \"three\"]"); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(a.IsArray()); EXPECT_EQ(3u, a.Size()); EXPECT_EQ(&a.GetAllocator(), &allocator); // Document b; b = a; // does not compile (!is_copy_assignable) Document b; b = std::move(a); EXPECT_TRUE(a.IsNull()); EXPECT_TRUE(b.IsArray()); EXPECT_EQ(3u, b.Size()); EXPECT_EQ(&a.GetAllocator(), (void*)0); EXPECT_EQ(&b.GetAllocator(), &allocator); b.Parse("{\"Foo\": \"Bar\", \"Baz\": 42}"); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(b.IsObject()); EXPECT_EQ(2u, b.MemberCount()); // Document c; c = a; // does not compile (see static_assert) Document c; c = std::move(b); EXPECT_TRUE(b.IsNull()); EXPECT_TRUE(c.IsObject()); EXPECT_EQ(2u, c.MemberCount()); EXPECT_EQ(&b.GetAllocator(), (void*)0); EXPECT_EQ(&c.GetAllocator(), &allocator); }
int main() { Document d; { AsyncDocumentParser<> parser(d); const char json1[] = " { \"hello\" : \"world\", \"t\" : tr"; //const char json1[] = " { \"hello\" : \"world\", \"t\" : trX"; // For test parsing error const char json2[] = "ue, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.14"; const char json3[] = "16, \"a\":[1, 2, 3, 4] } "; parser.ParsePart(json1, sizeof(json1) - 1); parser.ParsePart(json2, sizeof(json2) - 1); parser.ParsePart(json3, sizeof(json3) - 1); } if (d.HasParseError()) { std::cout << "Error at offset " << d.GetErrorOffset() << ": " << GetParseError_En(d.GetParseError()) << std::endl; return EXIT_FAILURE; } // Stringify the JSON to cout OStreamWrapper os(std::cout); Writer<OStreamWrapper> writer(os); d.Accept(writer); std::cout << std::endl; return EXIT_SUCCESS; }
void RankScene::onGetRankResponse(HttpClient * sender, HttpResponse *response) { if (!response) return; if (!response->isSucceed()) { log("response failed"); log("error buffer: %s", response->getErrorBuffer()); return; } string res = Global::toString(response->getResponseData()); Document d; d.Parse<0>(res.c_str()); if (d.HasParseError()) { CCLOG("GetParseError %s\n", d.GetParseError()); } if (d.IsObject() && d.HasMember("result") && d.HasMember("info")) { bool result = d["result"].GetBool(); if (!result) { CCLOG("Failed to login: %s\n", d["info"].GetString()); } else { setRankBoard(d["info"].GetString()); } } }
bool FileUtil::LoadFromFile(const Serializable::Ptr &source, const std::string &filePath) { using namespace rapidjson; std::ifstream stream(filePath); if (stream) { std::stringstream buffer; buffer << stream.rdbuf(); Document dom; dom.Parse(buffer.str().c_str()); if (dom.HasParseError()) { LOGE << "Error parsing json file " << filePath << ": " << dom.GetParseError(); return false; } if (!source->Load(&dom)) { LOGE << "Serialization failed!"; return false; } LOGD << filePath << " successfully deserialized!"; return true; } return false; }
void ParseGameHashLibraryFromFile(std::map<std::string, GameID>& GameHashLibraryOut) { SetCurrentDirectory(NativeStr(g_sHomeDir).c_str()); FILE* pf = NULL; fopen_s(&pf, RA_GAME_HASH_FILENAME, "rb"); if (pf != NULL) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("MD5List")) { const Value& List = doc["MD5List"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { if (iter->name.IsNull() || iter->value.IsNull()) continue; const std::string sMD5 = iter->name.GetString(); //GameID nID = static_cast<GameID>( std::strtoul( iter->value.GetString(), NULL, 10 ) ); // MUST BE STRING, then converted to uint. Keys are strings ONLY GameID nID = static_cast<GameID>(iter->value.GetUint()); GameHashLibraryOut[sMD5] = nID; } } fclose(pf); } }
/* **************************************************************************** * * parseAttributeValue - */ std::string parseAttributeValue(ConnectionInfo* ciP, ContextAttribute* caP) { Document document; OrionError oe; document.Parse(ciP->payload); if (document.HasParseError()) { alarmMgr.badInput(clientIp, "JSON parse error"); oe.reasonPhrase = ERROR_STRING_PARSERROR; oe.details = "Errors found in incoming JSON buffer"; ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } if (!document.IsObject() && !document.IsArray()) { alarmMgr.badInput(clientIp, "JSON parse error"); oe.fill(SccBadRequest, "Neither JSON Object nor JSON Array for attribute::value"); ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } caP->valueType = (document.IsObject())? orion::ValueTypeObject : orion::ValueTypeVector; parseContextAttributeCompoundValueStandAlone(document, caP, caP->valueType); return "OK"; }
TEST(Document, UnchangedOnParseError) { Document doc; doc.SetArray().PushBack(0, doc.GetAllocator()); ParseResult err = doc.Parse("{]"); EXPECT_TRUE(doc.HasParseError()); EXPECT_EQ(err.Code(), doc.GetParseError()); EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsArray()); EXPECT_EQ(doc.Size(), 1u); err = doc.Parse("{}"); EXPECT_FALSE(doc.HasParseError()); EXPECT_FALSE(err.IsError()); EXPECT_EQ(err.Code(), doc.GetParseError()); EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsObject()); EXPECT_EQ(doc.MemberCount(), 0u); }
bool testJson(const char *json, size_t &line, size_t &col) { StringStream ss(json); CursorStreamWrapper<StringStream> csw(ss); Document document; document.ParseStream(csw); bool ret = document.HasParseError(); if (ret) { col = csw.GetColumn(); line = csw.GetLine(); } return ret; }
::urbi::UValue XJson::decode(const std::string &json) { Document doc; doc.Parse<0>(json.c_str()); if (doc.HasParseError()) { send("throw \"Cannot parse JSON.\";"); // would return nil UValue } UrbiHandler handler; doc.Accept(handler); return handler.getResult(); }
virtual bool ParseDouble(const char* json, double* d) const { Document doc; #ifdef TEST_INSITU RapidjsonParseResult pr(json, strlen(json)); doc.ParseInsitu<TEST_PARSE_FLAG>(pr.buffer); #else doc.Parse<TEST_PARSE_FLAG>(json); #endif if (!doc.HasParseError() && doc.IsArray() && doc.Size() == 1 && doc[0].IsNumber()) { *d = doc[0].GetDouble(); return true; } return false; }
virtual bool ParseString(const char* json, std::string& s) const { Document doc; #ifdef TEST_INSITU RapidjsonParseResult pr(json, strlen(json)); doc.ParseInsitu<TEST_PARSE_FLAG>(pr.buffer); #else doc.Parse<TEST_PARSE_FLAG>(json); #endif if (!doc.HasParseError() && doc.IsArray() && doc.Size() == 1 && doc[0].IsString()) { s = std::string(doc[0].GetString(), doc[0].GetStringLength()); return true; } return false; }
/** * Merge one set of options into this one. * All settings in the input take precedence over anything currently stored. * @param json_string The serialised JSON string to merge from. * @return true iff successfully merged. */ bool Options::Merge(const char *json_string) { if (json_string) { Document d; d.Parse<0>(json_string); if (!d.HasParseError() && d.IsObject()) { //Loop through each family for (Value::ConstMemberIterator it = d.MemberBegin(); it != d.MemberEnd(); it++) { //Do we have a family of options? (e.g. an object) if (it->value.IsObject()) { SetFamily(it->name.GetString()); //Loop through each option for (Value::ConstMemberIterator optit = it->value.MemberBegin(); optit != it->value.MemberEnd(); optit++) { const char *optkey = optit->name.GetString(); switch (optit->value.GetType()) { case kFalseType: case kTrueType: Set(optkey, optit->value.GetBool()); case kNumberType: if (optit->value.IsInt()) { Set(optkey, optit->value.GetInt()); } else if (optit->value.IsNumber()) { Set(optkey, optit->value.GetDouble()); } else if (optit->value.IsBool()) { Set(optkey, optit->value.GetBool()); } break; case kStringType: Set(optkey, optit->value.GetString()); break; case kNullType: //Ignore break; default: Log(LOG_WARNING, "Ignoring unknown option %s of type %d", optkey, optit->value.GetType()); } } } else { Log(LOG_WARNING, "Ignoring unknown family %s of type %d", it->name.GetString(), it->value.GetType()); } } return true; } } return false; }
int Dynamo::PostReq(const std::string &op, const string &req) { // logdebug("req: \n%s", req.c_str()); // // char *ueReq = curl_easy_escape(curl, req.data(), (int) req.length()); // // if (NULL == ueReq) { // snprintf(lastErr, sizeof(lastErr), "curl_easy_escape failed"); // return -1; // } // // std::string data = ueReq; // curl_free (ueReq); if (0 != UpdateHead(op, req)) { return -1; } // logdebug("\ncommand=%s\nrequest=\n%s", op.c_str(), req.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.c_str()); // curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.length()); strRsp.clear(); CURLcode code = curl_easy_perform(curl); if (CURLE_OK != code) { snprintf(lastErr, sizeof(lastErr), "%s", curl_easy_strerror(code)); return -1; } // logdebug("\ncommand=%s\nresponse=\n%s", op.c_str(), strRsp.c_str()); Document d; d.Parse<0>(strRsp.c_str()); if (d.HasParseError()) { snprintf(lastErr, sizeof(lastErr), "json doc parse failed, %u", d.GetParseError()); return -1; } rsp.SetNull(); allocator.Clear(); rsp.CopyFrom(d, allocator); if (rsp.HasMember("__type")) { snprintf(lastErr, sizeof(lastErr), "dynamo return error: %s", rsp.FindMember("__type")->value.GetString()); return -1; } return 0; }
void Dlg_MemBookmark::ImportFromFile( std::string sFilename ) { FILE* pFile = nullptr; errno_t nErr = fopen_s( &pFile, sFilename.c_str(), "r" ); if ( pFile != nullptr ) { Document doc; doc.ParseStream( FileStream( pFile ) ); if ( !doc.HasParseError() ) { if ( doc.HasMember( "Bookmarks" ) ) { ClearAllBookmarks(); const Value& BookmarksData = doc[ "Bookmarks" ]; for ( SizeType i = 0; i < BookmarksData.Size(); ++i ) { MemBookmark* NewBookmark = new MemBookmark(); wchar_t buffer[ 256 ]; swprintf_s ( buffer, 256, L"%s", Widen( BookmarksData[ i ][ "Description" ].GetString() ).c_str() ); NewBookmark->SetDescription ( buffer ); NewBookmark->SetAddress( BookmarksData[ i ][ "Address" ].GetUint() ); NewBookmark->SetType( BookmarksData[ i ][ "Type" ].GetInt() ); NewBookmark->SetDecimal( BookmarksData[ i ][ "Decimal" ].GetBool() ); NewBookmark->SetValue( GetMemory( NewBookmark->Address(), NewBookmark->Type() ) ); NewBookmark->SetPrevious ( NewBookmark->Value() ); AddBookmark ( NewBookmark ); AddBookmarkMap( NewBookmark ); } if ( m_vBookmarks.size() > 0 ) PopulateList(); } else { ASSERT ( " !Invalid Bookmark File..." ); MessageBox( nullptr, _T("Could not load properly. Invalid Bookmark file."), _T("Error"), MB_OK | MB_ICONERROR ); return; } } fclose( pFile ); } }
bool Export(const char* data, const char* outFile) { Document document; document.Parse(data); if (document.HasParseError()) { ParseErrorCode err = document.GetParseError(); printf("pares error! %d %d", err, document.GetErrorOffset()); return false; } if (!document.IsObject()) { printf("error, not a object"); return false; } InitializeSdkObjects(); const Value& skel = document["Skeleton"]; if (!skel.IsNull()) { ExportBones(skel); } const Value& mesh = document["Mesh"]; if (!mesh.IsNull()) { for (uint32_t i = 0; i < mesh.Size(); i++) { ExportFbxMesh(mesh[i]); } } const Value& anim = document["Animation"]; if (!anim.IsNull()) { for (uint32_t i = 0; i < anim.Size(); i++) { ExportAnimation(anim[i]); } } SaveFbxFile(outFile); return true; }
bgfx_effect* effect_manager::load_effect(std::string name) { std::string full_name = name; if (full_name.length() < 5 || (full_name.compare(full_name.length() - 5, 5, ".json") != 0)) { full_name = full_name + ".json"; } std::string path; osd_subst_env(path, util::string_format("%s" PATH_SEPARATOR "effects" PATH_SEPARATOR, m_options.bgfx_path())); path += full_name; bx::CrtFileReader reader; if (!bx::open(&reader, path.c_str())) { printf("Unable to open effect file %s\n", path.c_str()); return nullptr; } int32_t size (bx::getSize(&reader)); char* data = new char[size + 1]; bx::read(&reader, reinterpret_cast<void*>(data), size); bx::close(&reader); data[size] = 0; Document document; document.Parse<kParseCommentsFlag>(data); delete [] data; if (document.HasParseError()) { std::string error(GetParseError_En(document.GetParseError())); printf("Unable to parse effect %s. Errors returned:\n", path.c_str()); printf("%s\n", error.c_str()); return nullptr; } bgfx_effect* effect = effect_reader::read_from_value(document, "Effect '" + name + "': ", m_shaders); if (effect == nullptr) { printf("Unable to load effect %s\n", path.c_str()); return nullptr; } m_effects[name] = effect; return effect; }
Sprites parseSprite(const std::string& image, const std::string& json) { using namespace rapidjson; Sprites sprites; // Parse the sprite image. const util::Image raster(image); if (!raster) { Log::Warning(Event::Sprite, "Could not parse sprite image"); return sprites; } Document doc; doc.Parse<0>(json.c_str()); if (doc.HasParseError()) { Log::Warning(Event::Sprite, std::string{ "Failed to parse JSON: " } + doc.GetParseError() + " at offset " + std::to_string(doc.GetErrorOffset())); return sprites; } else if (!doc.IsObject()) { Log::Warning(Event::Sprite, "Sprite JSON root must be an object"); return sprites; } else { for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) { const std::string name = { itr->name.GetString(), itr->name.GetStringLength() }; const Value& value = itr->value; if (value.IsObject()) { const uint16_t x = getUInt16(value, "x", 0); const uint16_t y = getUInt16(value, "y", 0); const uint16_t width = getUInt16(value, "width", 0); const uint16_t height = getUInt16(value, "height", 0); const double pixelRatio = getDouble(value, "pixelRatio", 1); const bool sdf = getBoolean(value, "sdf", false); auto sprite = createSpriteImage(raster, x, y, width, height, pixelRatio, sdf); if (sprite) { sprites.emplace(name, sprite); } } } } return sprites; }
bool LocalizationManager::ParseLanguage(const FString& language) { FString path = FPaths::GameContentDir() + "Languages/" + language + ".json"; FString buffer; FFileHelper::LoadFileToString(buffer, *path); Document doc; doc.Parse<0>(TCHAR_TO_ANSI(*buffer)); if (!doc.HasParseError()) if (doc.IsObject()) if (doc.HasMember("language")) if (doc["language"].IsString()){ FString langName = doc["language"].GetString(); LangDef langDef(langName); if (doc.HasMember("keys")){ if (doc["keys"].IsArray()){ SizeType numKeys = doc["keys"].Size(); const Value &keys = doc["keys"]; for (SizeType i = 0; i < numKeys; i++) if (keys[i].IsObject()) if (keys[i].HasMember("key")) if (keys[i]["key"].IsString()){ FString k = keys[i]["key"].GetString(); if (keys[i].HasMember("value")) if (keys[i]["value"].IsString()){ FString v = keys[i]["value"].GetString(); v = ChangeSpecialSimbols(v); langDef.AddString(k, v); } } } m_languages.Add(langDef); return true; } } return false; }
TEST(SchemaValidator, ValidateMetaSchema) { CrtAllocator allocator; char* json = ReadFile("draft-04/schema", allocator); Document d; d.Parse(json); ASSERT_FALSE(d.HasParseError()); SchemaDocument sd(d); SchemaValidator validator(sd); if (!d.Accept(validator)) { StringBuffer sb; validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); printf("Invalid schema: %s\n", sb.GetString()); printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); sb.Clear(); validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); printf("Invalid document: %s\n", sb.GetString()); ADD_FAILURE(); } CrtAllocator::Free(json); }
void ParseMyProgressFromFile(std::map<GameID, std::string>& GameProgressOut) { FILE* pf = nullptr; fopen_s(&pf, RA_MY_PROGRESS_FILENAME, "rb"); if (pf != nullptr) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response")) { //{"ID":"7","NumAch":"14","Earned":"10","HCEarned":"0"}, const Value& List = doc["Response"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10)); // KEYS MUST BE STRINGS const unsigned int nNumAchievements = iter->value["NumAch"].GetUint(); const unsigned int nEarned = iter->value["Earned"].GetUint(); const unsigned int nEarnedHardcore = iter->value["HCEarned"].GetUint(); std::stringstream sstr; sstr << nEarned; if (nEarnedHardcore > 0) sstr << " (" << std::to_string(nEarnedHardcore) << ")"; sstr << " / " << nNumAchievements; if (nNumAchievements > 0) { const int nNumEarnedTotal = nEarned + nEarnedHardcore; char bufPct[256]; sprintf_s(bufPct, 256, " (%1.1f%%)", (nNumEarnedTotal / static_cast<float>(nNumAchievements)) * 100.0f); sstr << bufPct; } GameProgressOut[nID] = sstr.str(); } } fclose(pf); } }
TEST(Document, ParseStream_AutoUTFInputStream) { // Any -> UTF8 FILE* fp = OpenEncodedFile("utf32be.json"); char buffer[256]; FileReadStream bis(fp, buffer, sizeof(buffer)); AutoUTFInputStream<unsigned, FileReadStream> eis(bis); Document d; d.ParseStream<0, AutoUTF<unsigned> >(eis); EXPECT_FALSE(d.HasParseError()); fclose(fp); char expected[] = "I can eat glass and it doesn't hurt me."; Value& v = d["en"]; EXPECT_TRUE(v.IsString()); EXPECT_EQ(sizeof(expected) - 1, v.GetStringLength()); EXPECT_EQ(0, StrCmp(expected, v.GetString())); // UTF8 -> UTF8 in memory StringBuffer bos; Writer<StringBuffer> writer(bos); d.Accept(writer); { // Condense the original file and compare. FILE *fp = OpenEncodedFile("utf8.json"); FileReadStream is(fp, buffer, sizeof(buffer)); Reader reader; StringBuffer bos2; Writer<StringBuffer> writer(bos2); reader.Parse(is, writer); fclose(fp); EXPECT_EQ(bos.GetSize(), bos2.GetSize()); EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); } }
IPResponeData TigerIPLocation::parseJson(const std::string json) { IPResponeData data = IPResponeData(); Document document; document.Parse<0>(json.c_str()); if (document.HasParseError()) { cocos2d::log("### json document parse error [%u]###", document.GetParseError()); return data; } if (document.IsObject()) { if (document.HasMember("countryCode")) { data._countryCode = document["countryCode"].GetString(); } } return data; }
/* **************************************************************************** * * parseBatchUpdate - */ std::string parseBatchUpdate(ConnectionInfo* ciP, BatchUpdate* burP) { Document document; document.Parse(ciP->payload); if (document.HasParseError()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } if (!document.IsObject()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill("BadRequest", "JSON Parse Error"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (document.ObjectEmpty()) { ErrorCode ec; alarmMgr.badInput(clientIp, "Empty JSON payload"); ec.fill("BadRequest", "empty payload"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (!document.HasMember("entities")) { ErrorCode ec; std::string details = "Invalid JSON payload, mandatory field /entities/ not found"; alarmMgr.badInput(clientIp, details); ec.fill("BadRequest", details); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (!document.HasMember("actionType")) { ErrorCode ec; std::string details = "Invalid JSON payload, mandatory field /actionType/ not found"; alarmMgr.badInput(clientIp, details); ec.fill("BadRequest", details); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter) { std::string name = iter->name.GetString(); std::string type = jsonParseTypeNames[iter->value.GetType()]; if (name == "entities") { std::string r = parseEntityVector(ciP, iter, &burP->entities, true); // param 4: attributes are allowed in payload if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else if (name == "actionType") { burP->updateActionType.set(iter->value.GetString()); } else { std::string description = std::string("Unrecognized field in JSON payload: /") + name + "/"; ErrorCode ec("BadRequest", description); alarmMgr.badInput(clientIp, description); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } return "OK"; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); ////////////////////////////////////////////////////////////////////////// /// 数据读取 SSIZE_T size; /* FILE* file1 = fopen("test.json", "wr");*/ unsigned char* ch = FileUtils::getInstance()->getFileData("test.json","r", &size); std::string data = std::string((const char* )ch, size); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// 数据解析成json格式数据 Document doc; ///< 创建一个Document对象 rapidJson的相关操作都在Document类中 doc.Parse<0>(data.c_str()); ///< 通过Parse方法将Json数据解析出来 if (doc.HasParseError()) { CCLOG("GetParseError %s\n",doc.GetParseError()); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// Json数据读取和更改-----对值操作 rapidjson::Value& valString = doc["hello1"]; ///< 读取键“hello”的值,根据我们的json文档,是一个字符串 if (valString.IsString()) ///< 判断是否是字符串 { const char* ch = valString.GetString(); log(ch); log(valString.GetString()); valString.SetString("newString"); log(valString.GetString()); } rapidjson::Value& valArray = doc["a"]; ///< 读取键“a”值,根据我们的json文档,是一个数组 if (valArray.IsArray()) ///< 判断val的类型 是否为数组 我们的Tollgate键对应的value实际为数组 { for (int i = 0; i < valArray.Capacity(); ++i) { rapidjson::Value& first = valArray[i]; ///< 获取到val中的第i个元素 根据我们这里的json文件 val中共有4个元素 CCLOG("%f", first.GetDouble()); ///< 将value转换成Double类型打印出来 结果为0.5 first.SetDouble(10.f); CCLOG("%f", first.GetDouble()); ///< 将value转换成Double类型打印出来 结果为0.5S } } ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// json数据操作---对键操作之添加成员对象 /// 添加一个String对象; rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); ///< 获取最初数据的分配器 rapidjson::Value strObject(rapidjson::kStringType); ///< 添加字符串方法1 strObject.SetString("love"); doc.AddMember("hello1", strObject, allocator); /* doc.AddMember("hello1", "love you", allocator); ///< 添加字符串方法2:往分配器中添加一个对象*/ /// 添加一个null对象 rapidjson::Value nullObject(rapidjson::kNullType); doc.AddMember("null", nullObject, allocator); ///< 往分配器中添加一个对象 /// 添加一个数组对象 rapidjson::Value array(rapidjson::kArrayType); ///< 创建一个数组对象 rapidjson::Value object(rapidjson::kObjectType); ///< 创建数组里面对象。 object.AddMember("id", 1, allocator); object.AddMember("name", "lai", allocator); object.AddMember("age", "12", allocator); object.AddMember("low", true, allocator); array.PushBack(object, allocator); doc.AddMember("player", array, allocator); ///< 将上述的数组内容添加到一个名为“player”的数组中 /// 在已有的数组中添加一个成员对象 rapidjson::Value& aArray1 = doc["a"]; aArray1.PushBack(2.0, allocator); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// json数据操作---对键操作之删除成员对象 /// 删除数组成员对象里面元素 rapidjson::Value& aArray2 = doc["a"]; ///< 读取键“a”值,根据我们的json文档,是一个数组 aArray2.PopBack(); ///< 删除数组最后一个成员对象 if (doc.RemoveMember("i")) ///< 删除键为“i”的成员变量 { log("delet i member ok!"); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// 将json数据重新写入文件中---先将文件删除,再写入内容 rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) system("del E:\cocos2d-x-3.2rc0\tests\cpp-empty-test\Resources\test.josn"); ///< 先将文件删除掉---之前重这个文件读取数据,因此确保这个文件存在了 FILE* file = fopen("test.json", "wb"); if (file) { fputs(buffer.GetString(), file); fclose(file); } #else if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) /// 原理差不多,就是先将文件清空,在写入。这里就不写了。 #endif ////////////////////////////////////////////////////////////////////////// return true; }
/* **************************************************************************** * * parseAttributeValue - */ std::string parseAttributeValue(ConnectionInfo* ciP, ContextAttribute* caP) { Document document; OrionError oe; document.Parse(ciP->payload); if (document.HasParseError()) { LM_W(("Bad Input (JSON parse error)")); oe.fill(SccBadRequest, "Errors found in incoming JSON buffer"); ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } if (!document.IsObject()) { LM_E(("Bad Input (JSON Parse Error)")); oe.fill(SccBadRequest, "Error parsing incoming JSON buffer"); ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } if (!document.HasMember("value")) { LM_W(("Bad Input (No attribute value specified")); oe.fill(SccBadRequest, "no attribute value specified"); ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter) { std::string name = iter->name.GetString(); std::string type = jsonParseTypeNames[iter->value.GetType()]; if (name != "value") { LM_W(("Bad Input (unexpected JSON field - accepting only 'value'")); oe.fill(SccBadRequest, "unexpected JSON field - accepting only /value/"); ciP->httpStatusCode = SccBadRequest;; return oe.render(ciP, ""); } if (type == "String") { caP->valueType = orion::ValueTypeString; caP->stringValue = iter->value.GetString(); } else if (type == "Number") { caP->numberValue = iter->value.GetDouble(); caP->valueType = orion::ValueTypeNumber; } else if (type == "True") { caP->boolValue = true; caP->valueType = orion::ValueTypeBoolean; } else if (type == "False") { caP->boolValue = false; caP->valueType = orion::ValueTypeBoolean; } else if (type == "Array") { caP->valueType = orion::ValueTypeVector; std::string r = parseContextAttributeCompoundValue(iter, caP, NULL); if (r != "OK") { LM_W(("Bad Input (json error in ContextAttributeObject::Vector")); return "json error in ContextAttributeObject::Vector"; } } else if (type == "Object") { caP->valueType = orion::ValueTypeObject; std::string r = parseContextAttributeCompoundValue(iter, caP, NULL); if (r != "OK") { LM_W(("Bad Input (json error in ContextAttributeObject::Object")); return "json error in ContextAttributeObject::Object"; } } } return "OK"; }