//--------------------------------------------------------------------------- TJSONObject *parseJsonValue (TJSONValue *value) { TJSONObject *jsonObj = new TJSONObject; TBytes jsonBytes = TEncoding::UTF8->GetBytes(value->ToString()); jsonObj->Parse(jsonBytes, 0); return jsonObj; }
// --------------------------------------------------------------------------- TJSONObject* __fastcall TNoteJSON::NoteToJSON(const TNote *ANote) { TJSONObject * jsonObj = new TJSONObject(); jsonObj->AddPair(TNames::Title, ANote->Title); jsonObj->AddPair(TNames::Content, ANote->Content); jsonObj->AddPair(TNames::Id, ANote->ID); return jsonObj; }
// --------------------------------------------------------------------------- TNote* __fastcall TNoteJSON::JSONToNote(const TJSONValue * AJSON) { TJSONObject * obj = static_cast<TJSONObject*>(const_cast<TJSONValue*>(AJSON)); TNote * note = new TNote( obj->Get(TNames::Title)->JsonValue->Value(), obj->Get(TNames::Content)->JsonValue->Value(), obj->Get(TNames::Id)->JsonValue->Value()); return note; }
void TNotesResource1::Post(TEndpointContext* AContext, TEndpointRequest* ARequest, TEndpointResponse* AResponse) { try { TJSONObject * lJson = NULL; if(ARequest->Body->TryGetObject(lJson)) { CheckNotesManager(AContext); TNote * lNote = TNoteJSON::JSONToNote(lJson); String lId = ""; FNotesStorage->AddNote(*lNote, lId); lJson = new TJSONObject(); lJson->AddPair(TNoteJSON::TNames::Id, lId); AResponse->Body->SetValue(lJson, true); } else { AResponse->RaiseBadRequest("JSON expected"); } } catch (...) { HandleException(); } }
void __fastcall TUserNotifyThread::Execute() { TJSONObject *Msg; String EventType; FreeOnTerminate = True; if (FWasAdded) EventType = "user_login"; else EventType = "user_logout"; //create a JSON object with a message describing the user login/logout event Msg = new TJSONObject(); Msg->AddPair(new TJSONPair("notificationType", EventType)); Msg->AddPair(new TJSONPair("user", FUserName)); //give time for the client's callback to be added or removed Sleep(1000); //send a message to all clients that a user either logged in, or logged out FServer->BroadcastMessage(CHAT_ROOM_ID, Msg); };
//--------------------------------------------------------------------------- void __fastcall TChatRoomForm::AdminMessageButtonClick(TObject *Sender) { String Msg; TJSONObject *JSONMsg; Msg = Trim(AdminMessageField->Text); //no message to send, so just exit if (Msg == EmptyStr) return; //wrap the message in a JSON object JSONMsg = new TJSONObject(); JSONMsg->AddPair(new TJSONPair("notificationType", "message")); JSONMsg->AddPair(new TJSONPair("from", SUPER_USER_NAME)); JSONMsg->AddPair(new TJSONPair("message", Msg)); //Send the typed message to all logged in users //NOTE: the call to broadcast should really be done in its own thread to avoid locking the UI if (ServerContainerForm->ChatRoomServer->BroadcastMessage(CHAT_ROOM_ID, JSONMsg)) AdminMessageField->Text = EmptyStr; else ShowMessage("Failed to broadcast message. Sorry!"); }
//--------------------------------------------------------------------------- //сохраняет текущий проект на диск void ProjectManager::saveProject(UnicodeString fileName) { //открываем файловым поток TFileStream *fs = new TFileStream(fileName, fmCreate); try { //заносим текущий проетк в JSON объект TJSONObject *js = new TJSONObject(); TJSONArray *criteriaNamesJSON = new TJSONArray(); TJSONArray *alternativeNamesJSON = new TJSONArray(); //добавляем имена критериев const vector<UnicodeString> &criteriaNames = getCurrentProject().getCriteriaNames(); vector<UnicodeString>::const_iterator iter; for (iter = criteriaNames.begin(); iter != criteriaNames.end(); ++iter) { criteriaNamesJSON->Add(*iter); } js->AddPair(L"criteriaNames", criteriaNamesJSON); //добавляем имена альтернатив const vector<UnicodeString> &alternativeNames = getCurrentProject().getAlternativeNames(); for (iter = alternativeNames.begin(); iter != alternativeNames.end(); ++iter) { alternativeNamesJSON->Add(*iter); } js->AddPair(L"alternativeNames", alternativeNamesJSON); //добавляем оценки критериев (баллы и рассчитаныый рейтинг(приоритеты)) Estimates &criteriaEstimates = currentProject->getCriteriaEstimates(); vector< vector<int> > &rates = criteriaEstimates.getRates(); vector<double> &priorities = criteriaEstimates.getPriorities(); TJSONObject *crteriaEstimatesJSON = new TJSONObject(); TJSONArray *crteriaEstimatesArray = new TJSONArray(); for (int i = 0; i < priorities.size(); ++i) { crteriaEstimatesArray->Add(FloatToStr(priorities[i])); } crteriaEstimatesJSON->AddPair(L"priorities", crteriaEstimatesArray); TJSONArray *crteriaRatesTable = new TJSONArray(); for (int i = 0; i < rates.size(); ++i) { vector<int> &v = rates[i]; TJSONArray *crteriaRatesRow = new TJSONArray(); for (int j = 0; j < v.size(); ++j) { crteriaRatesRow->Add(IntToStr(v[j])); } crteriaRatesTable->Add(crteriaRatesRow); } crteriaEstimatesJSON->AddPair(L"rates", crteriaRatesTable); js->AddPair(L"criteriaEstimates", crteriaEstimatesJSON); //добавляем оценки альтернатив vector<Estimates> alternativeEstimates = getCurrentProject().getAlternativeEstimates(); TJSONArray *tableData = new TJSONArray(); for (int i = 0; i < alternativeEstimates.size(); i++) { TJSONObject *alternativeEstimatesJSON = new TJSONObject(); TJSONArray *prioritiesJSON = new TJSONArray(); const vector<double> &priorities = alternativeEstimates[i].getPriorities(); for (int j = 0; j < priorities.size(); j++) { prioritiesJSON->Add(FloatToStr(priorities[j])); } alternativeEstimatesJSON->AddPair("priorities", prioritiesJSON); vector< vector<int> > &rates = alternativeEstimates[i].getRates(); TJSONArray *alternativeRatesTable = new TJSONArray(); for (int j = 0; j < rates.size(); ++j) { vector<int> &v = rates[j]; TJSONArray *alternativeRatesRow = new TJSONArray(); for (int k = 0; k < v.size(); ++k) { alternativeRatesRow->Add(IntToStr(v[k])); } alternativeRatesTable->Add(alternativeRatesRow); } alternativeEstimatesJSON->AddPair(L"rates", alternativeRatesTable); tableData->AddElement(alternativeEstimatesJSON); } js->AddPair(L"alternativeEstimates", tableData); //сохраняем имя и метод js->AddPair(L"projectName", getCurrentProject().getName()); js->AddPair(L"method", IntToStr(getCurrentProject().getMethod())); //сохраняем JSON объект в файл как строку UnicodeString projectJSON = js->ToString(); fs->Write(projectJSON.BytesOf(), projectJSON.Length()); js->Free(); //устанавливаем, что проект сохранён setIsCurrentProjectSaved(true); } __finally { fs->Free(); } }
//--------------------------------------------------------------------------- //загрузка проекта из файла, действия аналогичные, что и в сохранении, только //в обратном порядке(парсим JSON объект и заполняем пустой проект) Project & ProjectManager::loadProject(UnicodeString fileName) { TFileStream *fs = new TFileStream(fileName, fmOpenRead); try { int n = fs->Size; char *chars = new char[n+1]; fs->Read(chars, n); chars[n] = '\0'; UnicodeString str(chars); TJSONObject *js = (TJSONObject*) TJSONObject::ParseJSONValue(str); closeProject(); currentProject = new Project(); TJSONArray *criteriaNamesJSON = (TJSONArray*) js->Get(L"criteriaNames")->JsonValue; vector<UnicodeString> &criteriaNames= getCurrentProject().getCriteriaNames(); for (int i = 0; i < criteriaNamesJSON->Size(); ++i) { criteriaNames.push_back(criteriaNamesJSON->Get(i)->Value()); } TJSONArray *alternativeNamesJSON = (TJSONArray*) js->Get(L"alternativeNames")->JsonValue; vector<UnicodeString> &alternativeNames = getCurrentProject().getAlternativeNames(); for (int i = 0; i < alternativeNamesJSON->Size(); ++i) { alternativeNames.push_back(alternativeNamesJSON->Get(i)->Value()); } TJSONObject *crteriaEstimatesJSON = (TJSONObject*) js->Get(L"criteriaEstimates")->JsonValue; TJSONArray *crteriaEstimatesArray = (TJSONArray*) crteriaEstimatesJSON->Get(L"priorities")->JsonValue; Estimates &criteriaEstimates = currentProject->getCriteriaEstimates(); vector<double> &priorities = criteriaEstimates.getPriorities(); for (int i = 0; i < crteriaEstimatesArray->Size(); ++i) { priorities.push_back(StrToFloat(crteriaEstimatesArray->Get(i)->Value())); } TJSONArray *crteriaRatesTable = (TJSONArray*) crteriaEstimatesJSON->Get(L"rates")->JsonValue; vector< vector<int> > &rates = criteriaEstimates.getRates(); for (int i = 0; i < crteriaRatesTable->Size(); ++i) { vector<int> v; TJSONArray *crteriaRatesRow = (TJSONArray*) crteriaRatesTable->Get(i); for (int j = 0; j < crteriaRatesRow->Size(); ++j) { v.push_back(StrToInt(crteriaRatesRow->Get(j)->Value())); } rates.push_back(v); } TJSONArray *alternativeEstimatesJSON = (TJSONArray*) js->Get(L"alternativeEstimates")->JsonValue; vector<Estimates> &alternativeEstimates = getCurrentProject().getAlternativeEstimates(); for (int i = 0; i < alternativeEstimatesJSON->Size(); ++i) { TJSONObject *alternativeJSON = (TJSONObject*) alternativeEstimatesJSON->Get(i); alternativeEstimates.push_back(Estimates()); TJSONArray *prioritiesJSON = (TJSONArray*) alternativeJSON->Get(L"priorities")->JsonValue; vector<double> &priorities = alternativeEstimates[i].getPriorities(); for (int j = 0; j < prioritiesJSON->Size(); ++j) { UnicodeString str = prioritiesJSON->Get(j)->Value(); priorities.push_back(StrToFloat(str)); } TJSONArray *alternativeRatesTable = (TJSONArray*) alternativeJSON->Get(L"rates")->JsonValue; vector< vector<int> > &rates = alternativeEstimates[i].getRates(); for (int j = 0; j < alternativeRatesTable->Size(); ++j) { vector<int> v; TJSONArray *alternativeRatesRow = (TJSONArray*) alternativeRatesTable->Get(j); for (int k = 0; k < alternativeRatesRow->Size(); ++k) { v.push_back(StrToInt(alternativeRatesRow->Get(k)->Value())); } rates.push_back(v); } } getCurrentProject().setName(js->Get(L"projectName")->JsonValue->Value()); getCurrentProject().setMethod(StrToInt(js->Get(L"method")->JsonValue->Value())); delete [] chars; js->Free(); setIsProjectOpen(true); setIsCurrentProjectSaved(true); return getCurrentProject(); } __finally { fs->Free(); } return getCurrentProject(); }
//--------------------------------------------------------------------------- void __fastcall TMainForm::ParseJSON (const UnicodeString& fileName) { TStringList *jsonText = new TStringList; jsonText->LoadFromFile(fileName); TBytes jsonBytes = TEncoding::UTF8->GetBytes(jsonText->Text); delete jsonText; TJSONObject *json = new TJSONObject; json->Parse(jsonBytes, 0); TJSONObject *topObjectValueObj; // Points topObjectValueObj = parseJsonValue(json->Get("points")->JsonValue); for (int i = 0; i < topObjectValueObj->Size(); ++i) { TJSONPair *pair = topObjectValueObj->Get(i); TJSONArray *array = jsonArrayFromPair(pair); // Vertice *point = new Vertice(INTVALARR(array, 0), // INTVALARR(array, 1), // INTVALARR(array, 2)); // // points[pair->JsonString->Value()] = point; } delete topObjectValueObj; // Edges topObjectValueObj = parseJsonValue(json->Get("edges")->JsonValue); map<UnicodeString, TColor> *colors = new map<UnicodeString, TColor>; (*colors)["red"] = clRed; (*colors)["black"] = clBlack; (*colors)["green"] = clGreen; (*colors)["blue"] = clBlue; (*colors)["fuchsia"] = clFuchsia; (*colors)["lime"] = clLime; for (int i = 0; i < topObjectValueObj->Size(); ++i) { TJSONPair *pair = topObjectValueObj->Get(i); TJSONObject *object = parseJsonValue(pair->JsonValue); TJSONArray *array = jsonArrayFromPair(object->Get("vertices")); // Edge *edge = new Edge (points[STRVALARR(array, 0)], points[STRVALARR(array, 1)]); // // if (object->Get("color")) { // edge->setPen((*colors)[STRVALOBJ(object, "color")], 1, psSolid); // } // // edges[pair->JsonString->Value()] = edge; } delete colors; delete topObjectValueObj; // Objects topObjectValueObj = parseJsonValue(json->Get("objects")->JsonValue); for (int i = 0; i < topObjectValueObj->Size(); ++i) { TJSONPair *pair = topObjectValueObj->Get(i); TJSONObject *object = parseJsonValue(pair->JsonValue); TJSONArray *array = jsonArrayFromPair(object->Get("edges")); GraphicObject *graphicObject = new GraphicObject; for (int j = 0; j < array->Size(); ++j) { graphicObject->addEdge(edges[STRVALARR(array, j)]); } objects[pair->JsonString->Value()] = graphicObject; } delete topObjectValueObj; }