public override void OnSuccess(WWWResult www) { if (this.Error()) { return; } FlowNode_TowerStartQuest.Json_TowerStartQuest jsonTowerStartQuest = (FlowNode_TowerStartQuest.Json_TowerStartQuest)null; WebAPI.JSON_BodyResponse <FlowNode_TowerStartQuest.Json_TowerResume> jsonBodyResponse = (WebAPI.JSON_BodyResponse <FlowNode_TowerStartQuest.Json_TowerResume>)null; if (this.mResume) { jsonBodyResponse = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_TowerStartQuest.Json_TowerResume> >(www.text); if (jsonBodyResponse.body.pdeck != null) { MonoSingleton <GameManager> .Instance.TowerResuponse.Deserialize(jsonBodyResponse.body.pdeck); } if (jsonBodyResponse.body.edeck != null) { MonoSingleton <GameManager> .Instance.TowerResuponse.Deserialize(jsonBodyResponse.body.edeck); } jsonTowerStartQuest = new FlowNode_TowerStartQuest.Json_TowerStartQuest(); jsonTowerStartQuest.btlinfo = jsonBodyResponse.body.btlinfo; jsonTowerStartQuest.btlid = jsonBodyResponse.body.btlid; MonoSingleton <GameManager> .Instance.TowerResuponse.round = jsonBodyResponse.body.round; } WebAPI.JSON_BodyResponse <FlowNode_TowerStartQuest.Json_TowerStartQuest> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_TowerStartQuest.Json_TowerStartQuest> >(www.text); if (jsonObject.body == null) { this.OnRetry(); } else { if (jsonTowerStartQuest == null) { jsonTowerStartQuest = jsonObject.body; } if (this.mResume && jsonBodyResponse == null) { jsonTowerStartQuest.btlinfo = jsonBodyResponse.body.btlinfo; } Network.RemoveAPI(); BattleCore.Json_Battle json = new BattleCore.Json_Battle(); json.btlid = jsonTowerStartQuest.btlid; json.btlinfo = (BattleCore.Json_BtlInfo)jsonTowerStartQuest.btlinfo; if (json.btlinfo != null) { json.btlinfo.qid = jsonTowerStartQuest.btlinfo.floor_iname; } this.StartCoroutine(this.StartScene(json)); } }
// ================================================================================================================ // PUBLIC INTERFACE ----------------------------------------------------------------------------------------------- public static bool matchesInput(StringBuilder input, int position) { return(JSONParser.compareStringValue(CHAR_START.ToString(), input, position + JSONParser.countWhitespaceCharacters(input, position))); }
public override void OnSuccess(WWWResult www) { DebugUtility.Log(nameof(OnSuccess)); if (Network.IsError) { switch (Network.ErrCode) { case Network.EErrCode.MultiMaintenance: case Network.EErrCode.VsMaintenance: Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(6000); break; case Network.EErrCode.MultiVersionMismatch: case Network.EErrCode.VS_Version: Network.RemoveAPI(); Network.ResetError(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(5000); break; case Network.EErrCode.RoomFailedMakeRoom: Network.RemoveAPI(); Network.ResetError(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(4800); break; case Network.EErrCode.RoomIllegalComment: case Network.EErrCode.VS_IllComment: if (this.API == FlowNode_MultiPlayAPI.EAPI.MAKE) { string str = LocalizedText.Get("sys.DEFAULT_ROOM_COMMENT"); PlayerPrefs.SetString(PlayerData.ROOM_COMMENT_KEY, str); } Network.RemoveAPI(); Network.ResetError(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(4801); break; case Network.EErrCode.RoomNoRoom: case Network.EErrCode.VS_NoRoom: Network.RemoveAPI(); Network.ResetError(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(4900); break; case Network.EErrCode.VS_NotLINERoomInfo: Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(7000); break; case Network.EErrCode.VS_FailRoomID: Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(8000); break; case Network.EErrCode.VS_NotPhotonAppID: Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(9000); break; case Network.EErrCode.VS_FaildSeasonGift: Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(10000); break; default: this.OnFailed(); break; } } else { if (this.API == FlowNode_MultiPlayAPI.EAPI.MAKE) { WebAPI.JSON_BodyResponse <ReqMPRoomMake.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqMPRoomMake.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } GlobalVars.SelectedMultiPlayRoomID = jsonObject.body.roomid; GlobalVars.SelectedMultiPlayPhotonAppID = jsonObject.body.app_id; GlobalVars.SelectedMultiPlayRoomName = jsonObject.body.token; DebugUtility.Log("MakeRoom RoomID:" + (object)GlobalVars.SelectedMultiPlayRoomID + " AppID:" + GlobalVars.SelectedMultiPlayPhotonAppID + " Name:" + GlobalVars.SelectedMultiPlayRoomName); } else if (this.API == FlowNode_MultiPlayAPI.EAPI.ROOM) { WebAPI.JSON_BodyResponse <ReqMPRoom.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqMPRoom.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } FlowNode_MultiPlayAPI.RoomList = jsonObject.body; if (FlowNode_MultiPlayAPI.RoomList == null) { DebugUtility.Log("ListRoom null"); } else if (FlowNode_MultiPlayAPI.RoomList.rooms == null) { DebugUtility.Log("ListRoom rooms null"); } else { DebugUtility.Log("ListRoom num:" + (object)FlowNode_MultiPlayAPI.RoomList.rooms.Length); } } else if (this.API == FlowNode_MultiPlayAPI.EAPI.JOIN) { WebAPI.JSON_BodyResponse <ReqMPRoomJoin.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqMPRoomJoin.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } if (jsonObject.body.quest == null || string.IsNullOrEmpty(jsonObject.body.quest.iname)) { this.OnFailed(); return; } GlobalVars.SelectedQuestID = jsonObject.body.quest.iname; GlobalVars.SelectedMultiPlayPhotonAppID = jsonObject.body.app_id; GlobalVars.SelectedMultiPlayRoomName = jsonObject.body.token; DebugUtility.Log("JoinRoom AppID:" + GlobalVars.SelectedMultiPlayPhotonAppID + " Name:" + GlobalVars.SelectedMultiPlayRoomName); } else if (this.API != FlowNode_MultiPlayAPI.EAPI.UPDATE && this.API != FlowNode_MultiPlayAPI.EAPI.VERSION) { if (this.API == FlowNode_MultiPlayAPI.EAPI.VERSUS_START) { WebAPI.JSON_BodyResponse <ReqVersusStart.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqVersusStart.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } GlobalVars.SelectedMultiPlayPhotonAppID = jsonObject.body.app_id; switch (GlobalVars.SelectedMultiPlayVersusType) { case VERSUS_TYPE.Free: GlobalVars.SelectedQuestID = jsonObject.body.maps.free; break; case VERSUS_TYPE.Friend: GlobalVars.SelectedQuestID = jsonObject.body.maps.friend; break; } DebugUtility.Log("MakeRoom RoomID: AppID:" + GlobalVars.SelectedMultiPlayPhotonAppID + "/ QuestID:" + GlobalVars.SelectedQuestID); } else if (this.API == FlowNode_MultiPlayAPI.EAPI.VERSUS_MAKE) { WebAPI.JSON_BodyResponse <ReqVersusMake.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqVersusMake.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } GlobalVars.SelectedMultiPlayRoomID = jsonObject.body.roomid; GlobalVars.SelectedMultiPlayRoomName = jsonObject.body.token; if (GlobalVars.SelectedMultiPlayVersusType == VERSUS_TYPE.Friend) { GlobalVars.EditMultiPlayRoomPassCode = "1"; } } else if (this.API == FlowNode_MultiPlayAPI.EAPI.VERSUS_JOIN) { WebAPI.JSON_BodyResponse <ReqVersusRoomJoin.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqVersusRoomJoin.Response> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnFailed(); return; } if (jsonObject.body.quest == null || string.IsNullOrEmpty(jsonObject.body.quest.iname)) { this.OnFailed(); return; } GlobalVars.SelectedQuestID = jsonObject.body.quest.iname; GlobalVars.SelectedMultiPlayPhotonAppID = jsonObject.body.app_id; GlobalVars.SelectedMultiPlayRoomName = jsonObject.body.token; DebugUtility.Log("JoinRoom AppID:" + GlobalVars.SelectedMultiPlayPhotonAppID + " Name:" + GlobalVars.SelectedMultiPlayRoomName); } else if (this.API != FlowNode_MultiPlayAPI.EAPI.VERSUS_LINE_REQ && this.API != FlowNode_MultiPlayAPI.EAPI.VERSUS_LINE_MAKE) { if (this.API == FlowNode_MultiPlayAPI.EAPI.VERSUS_STATUS) { WebAPI.JSON_BodyResponse <ReqVersusStatus.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqVersusStatus.Response> >(www.text); if (jsonObject == null) { this.OnFailed(); return; } GameManager instance = MonoSingleton <GameManager> .Instance; instance.Player.SetTowerMatchInfo(jsonObject.body.floor, jsonObject.body.key, jsonObject.body.wincnt, jsonObject.body.is_give_season_gift != 0); instance.VersusTowerMatchBegin = !string.IsNullOrEmpty(jsonObject.body.vstower_id); instance.VersusTowerMatchReceipt = jsonObject.body.is_season_gift != 0; instance.VersusTowerMatchName = jsonObject.body.tower_iname; instance.VersusTowerMatchEndAt = jsonObject.body.end_at; GlobalVars.SelectedQuestID = jsonObject.body.vstower_id; } else if (this.API == FlowNode_MultiPlayAPI.EAPI.VERSUS_SEASON) { WebAPI.JSON_BodyResponse <ReqVersusSeason.Response> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqVersusSeason.Response> >(www.text); if (jsonObject == null) { this.OnFailed(); return; } PlayerData player = MonoSingleton <GameManager> .Instance.Player; player.VersusSeazonGiftReceipt = false; player.UnreadMailPeriod |= jsonObject.body.unreadmail == 1; } } } Network.RemoveAPI(); this.Success(); } }
public static void GetAuthorizationCodeAsync(string clientId, Action <AuthCodeResponse> callback) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentException("clientId is null or empty.", "clientId"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (string.IsNullOrEmpty(UnityConnect.instance.GetAccessToken())) { throw new InvalidOperationException("User is not logged in or user status invalid."); } string url = string.Format("{0}/v1/oauth2/authorize", UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudIdentity)); AsyncHTTPClient client = new AsyncHTTPClient(url); client.postData = string.Format("client_id={0}&response_type=code&format=json&access_token={1}&prompt=none", clientId, UnityConnect.instance.GetAccessToken()); client.doneCallback = delegate(IAsyncHTTPClient c) { AuthCodeResponse response = new AuthCodeResponse(); if (!c.IsSuccess()) { response.Exception = new InvalidOperationException("Failed to call Unity ID to get auth code."); } else { try { var json = new JSONParser(c.text).Parse(); if (json.ContainsKey("code") && !json["code"].IsNull()) { response.AuthCode = json["code"].AsString(); } else if (json.ContainsKey("message")) { response.Exception = new InvalidOperationException(string.Format("Error from server: {0}", json["message"].AsString())); } else if (json.ContainsKey("location") && !json["location"].IsNull()) { UnityConnectConsentView consentView = UnityConnectConsentView.ShowUnityConnectConsentView(json["location"].AsString()); if (!string.IsNullOrEmpty(consentView.Code)) { response.AuthCode = consentView.Code; } else if (!string.IsNullOrEmpty(consentView.Error)) { response.Exception = new InvalidOperationException(string.Format("Error from server: {0}", consentView.Error)); } else { response.Exception = new InvalidOperationException("Consent Windows was closed unexpected."); } } else { response.Exception = new InvalidOperationException("Unexpected response from server."); } } catch (JSONParseException) { response.Exception = new InvalidOperationException("Unexpected response from server: Failed to parse JSON."); } } callback(response); }; client.Begin(); }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { switch (Network.ErrCode) { case Network.EErrCode.NoGacha: this.OnFailed(); break; case Network.EErrCode.GachaCostShort: this.OnBack(); break; case Network.EErrCode.GachaItemMax: this.OnBack(); break; case Network.EErrCode.GachaPaidLimitOver: this.PaidGachaLimitOver(); break; default: this.OnRetry(); break; } } else { WebAPI.JSON_BodyResponse <Json_GachaResult> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <Json_GachaResult> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); try { MonoSingleton <GameManager> .Instance.Deserialize(jsonObject.body); } catch (Exception ex) { DebugUtility.LogException(ex); this.Failure(); return; } List <GachaDropData> gachaDropDataList = new List <GachaDropData>(); foreach (Json_DropInfo json in jsonObject.body.add) { GachaDropData gachaDropData = new GachaDropData(); if (gachaDropData.Deserialize(json)) { gachaDropDataList.Add(gachaDropData); } } List <GachaDropData> a_dropMails = new List <GachaDropData>(); if (jsonObject.body.addMail != null) { foreach (Json_DropInfo json in jsonObject.body.addMail) { GachaDropData gachaDropData = new GachaDropData(); if (gachaDropData.Deserialize(json)) { a_dropMails.Add(gachaDropData); } } } GachaReceiptData a_receipt = new GachaReceiptData(); a_receipt.Deserialize(jsonObject.body.receipt); GachaResultData.Init(gachaDropDataList, a_dropMails, a_receipt); CultureInfo.CurrentCulture.TextInfo.ToTitleCase(a_receipt.type); AnalyticsManager.TrackSummonComplete(); MonoSingleton <GameManager> .Instance.Player.OnGacha(this.mCurrentGachaType, this.mCurrentNum); this.StartCoroutine(this.AsyncGachaResultData(gachaDropDataList)); } }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { Network.EErrCode errCode = Network.ErrCode; this.OnRetry(); } else { WebAPI.JSON_BodyResponse <FlowNode_ReqConceptCard.Json_ConceptCardList> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_ReqConceptCard.Json_ConceptCardList> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); try { MonoSingleton <GameManager> .Instance.Deserialize(jsonObject.body.cards, this.mIsDataOverride); MonoSingleton <GameManager> .Instance.Deserialize(jsonObject.body.materials, this.mIsDataOverride); GlobalVars.IsDirtyConceptCardData.Set(false); } catch (Exception ex) { DebugUtility.LogException(ex); return; } this.StartCoroutine(this.DownloadAssetsAndOutputPin()); } }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { Network.EErrCode errCode = Network.ErrCode; this.OnRetry(); } else { WebAPI.JSON_BodyResponse <JSON_TrophyResponse> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <JSON_TrophyResponse> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); if (jsonObject.body == null) { this.OnRetry(); } else if (jsonObject.body.trophyprogs == null) { Network.RemoveAPI(); this.Success(); } else { GameManager instance = MonoSingleton <GameManager> .Instance; for (int index1 = 0; index1 < jsonObject.body.trophyprogs.Length; ++index1) { JSON_TrophyProgress trophyprog = jsonObject.body.trophyprogs[index1]; if (trophyprog != null) { if (instance.MasterParam.GetTrophy(trophyprog.iname) == null) { DebugUtility.LogError("存在しないミッション:" + trophyprog.iname); } else { TrophyState trophyCounter = instance.Player.GetTrophyCounter(instance.MasterParam.GetTrophy(trophyprog.iname), false); for (int index2 = 0; index2 < trophyprog.pts.Length && index2 < trophyCounter.Count.Length; ++index2) { trophyCounter.Count[index2] = trophyprog.pts[index2]; } trophyCounter.StartYMD = trophyprog.ymd; trophyCounter.IsEnded = trophyprog.rewarded_at != 0; if (trophyprog.rewarded_at != 0) { try { trophyCounter.RewardedAt = trophyprog.rewarded_at.FromYMD(); } catch { trophyCounter.RewardedAt = DateTime.MinValue; } } else { trophyCounter.RewardedAt = DateTime.MinValue; } } } } Network.RemoveAPI(); this.Success(); } } }
//functionforn video streaming private void LoadJSONBookData(string jsonBookUrl) { Debug.Log("inside json parsing "); // Gets the full book json url string fullBookURL = JsonServerUrl + jsonBookUrl; if(!mIsJSONRequested){ // Gets the json book info from the url mJsonBookInfo = new WWW(fullBookURL); mIsJSONRequested = true; Debug.Log(fullBookURL); } //if(mJsonBookInfo.progress >= 1) //{ if(mJsonBookInfo.error == null ) { Debug.Log("json parsing started"); // Parses the json Object JSONParser parser = new JSONParser(); BookData bookData = parser.ParseString(mJsonBookInfo.text); //var str = parser.ParseString(mJsonBookInfo.text); //Debug.Log(str.v); mBookData = bookData; //Debug.Log(mBookData.BookTitle); // Updates state variables //mIsLoadingBookData = false; // Updates the BookData info in the augmented object mBookInformationParser.UpdateBookData(bookData); //mIsLoadingBookThumb = true; }else { Debug.LogError("Error downloading json"); //mIsLoadingBookData = false; } //} }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { Network.EErrCode errCode = Network.ErrCode; switch (errCode) { case Network.EErrCode.VS_NotSelfBattle: this.OnFailed(); break; case Network.EErrCode.VS_NotPlayer: this.OnFailed(); break; case Network.EErrCode.VS_NotQuestInfo: this.OnFailed(); break; case Network.EErrCode.VS_NotQuestData: this.OnFailed(); break; case Network.EErrCode.VS_BattleNotEnd: this.OnFailed(); break; case Network.EErrCode.VS_ComBattleEnd: this.OnFailed(); break; case Network.EErrCode.VS_TowerNotPlay: this.OnFailed(); break; case Network.EErrCode.VS_NotContinuousEnemy: this.OnFailed(); break; case Network.EErrCode.VS_RowerNotMatching: this.OnFailed(); break; default: switch (errCode - 3800) { case Network.EErrCode.Success: this.OnBack(); return; case Network.EErrCode.Unknown: this.OnBack(); return; case Network.EErrCode.Version: this.OnFailed(); return; case Network.EErrCode.AssetVersion: this.OnBack(); return; case Network.EErrCode.NoVersionDbg: this.OnFailed(); return; case Network.EErrCode.Unknown | Network.EErrCode.NoVersionDbg: this.OnBack(); return; default: switch (errCode - 202) { case Network.EErrCode.Success: case Network.EErrCode.Unknown: case Network.EErrCode.AssetVersion: case Network.EErrCode.NoVersionDbg: this.OnMultiMaintenance(); return; default: switch (errCode - 3300) { case Network.EErrCode.Success: this.OnBack(); return; case Network.EErrCode.Unknown: this.OnBack(); return; case Network.EErrCode.AssetVersion: this.OnBack(); return; default: switch (errCode - 12001) { case Network.EErrCode.Success: this.OnFailed(); return; case Network.EErrCode.Version: CriticalSection.Leave(CriticalSections.SceneChange); Network.RemoveAPI(); ((Behaviour)this).set_enabled(false); this.ActivateOutputLinks(600); return; default: if (errCode != Network.EErrCode.NotLocation) { if (errCode != Network.EErrCode.NotGpsQuest) { if (errCode != Network.EErrCode.QuestEnd) { if (errCode != Network.EErrCode.NoBtlInfo) { if (errCode == Network.EErrCode.MultiVersionMismatch) { this.OnMismatchVersion(); return; } this.OnRetry(); return; } this.OnFailed(); return; } this.OnFailed(); return; } CriticalSection.Leave(CriticalSections.SceneChange); Network.RemoveAPI(); Network.ResetError(); this.ActivateOutputLinks(400); ((Behaviour)this).set_enabled(false); return; } this.OnBack(); return; } } } } } } else if (this.mReqID == 30) { Network.RemoveAPI(); this.ActivateOutputLinks(5); } else { string text = www.text; DebugMenu.Log("API", "StartQuest:" + www.text); WebAPI.JSON_BodyResponse <BattleCore.Json_Battle> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <BattleCore.Json_Battle> >(www.text); if (jsonObject.body == null) { this.OnRetry(); } else { Network.RemoveAPI(); this.ActivateOutputLinks(5); this.SetVersusAudienceParam(text); if (this.mResume && (MonoSingleton <GameManager> .Instance.Player.TutorialFlags & 1L) == 0L && jsonObject.body.btlinfo.qid == "QE_OP_0002") { MonoSingleton <GameManager> .Instance.CompleteTutorialStep(); } this.StartCoroutine(this.StartScene(jsonObject.body)); } } }
public bool Initialize(BattleCore core, MapParam param) { this.mBattle = core; this.MapSceneName = param.mapSceneName; this.BattleSceneName = param.battleSceneName; this.EventSceneName = param.eventSceneName; this.BGMName = param.bgmName; this.mWinMonitorCondition.Clear(); this.mLoseMonitorCondition.Clear(); if (string.IsNullOrEmpty(param.mapSceneName)) { DebugUtility.LogError("not found mapdata."); return(false); } string path1 = AssetPath.LocalMap(param.mapSceneName); string src1 = AssetManager.LoadTextData(path1); if (src1 == null) { DebugUtility.LogError("Failed to load " + path1); return(false); } if (!this.Deserialize(JSONParser.parseJSONObject <JSON_Map>(src1))) { DebugUtility.LogError("Failed to load " + path1); return(false); } string path2 = AssetPath.LocalMap(param.mapSetName); string src2 = AssetManager.LoadTextData(path2); if (src2 == null) { DebugUtility.LogError("マップ配置情報\"" + path2 + "\"に存在しない"); return(false); } JSON_MapUnit jsonObject = JSONParser.parseJSONObject <JSON_MapUnit>(src2); if (jsonObject == null) { DebugUtility.LogError("マップ配置情報\"" + path2 + "\"のパースに失敗"); return(false); } if (jsonObject.enemy == null && jsonObject.arena == null) { DebugUtility.LogError("敵ユニットの配置情報がマップ配置情報\"" + path2 + "\"に存在しない"); return(false); } if (jsonObject.party != null) { this.mPartyUnitSettings = new List <UnitSetting>(jsonObject.party.Length); for (int index = 0; index < jsonObject.party.Length; ++index) { this.mPartyUnitSettings.Add(new UnitSetting(jsonObject.party[index])); } } if (jsonObject.party_subs != null && jsonObject.party_subs.Length != 0) { this.mPartyUnitSubSettings = new List <UnitSubSetting>(jsonObject.party_subs.Length); foreach (JSON_MapPartySubCT partySub in jsonObject.party_subs) { this.mPartyUnitSubSettings.Add(new UnitSubSetting(partySub)); } } if (jsonObject.tricks != null && jsonObject.tricks.Length != 0) { this.mTrickSettings = new List <TrickSetting>(jsonObject.tricks.Length); foreach (JSON_MapTrick trick in jsonObject.tricks) { this.mTrickSettings.Add(new TrickSetting(trick)); } } if (jsonObject.enemy != null) { jsonObject.enemy = jsonObject.ReplacedRandEnemy(this.mRandDeckResult, true); this.mNPCUnitSettings = new List <NPCSetting>(jsonObject.enemy.Length); for (int index = 0; index < jsonObject.enemy.Length; ++index) { this.mNPCUnitSettings.Add(new NPCSetting(jsonObject.enemy[index])); } } if (jsonObject.arena != null) { this.mArenaUnitSettings = new List <UnitSetting>(jsonObject.arena.Length); for (int index = 0; index < jsonObject.arena.Length; ++index) { UnitSetting unitSetting = new UnitSetting(); unitSetting.uniqname = (OString)jsonObject.arena[index].name; unitSetting.ai = (OString)jsonObject.arena[index].ai; unitSetting.pos.x = (OInt)jsonObject.arena[index].x; unitSetting.pos.y = (OInt)jsonObject.arena[index].y; unitSetting.dir = (OInt)jsonObject.arena[index].dir; unitSetting.waitEntryClock = (OInt)jsonObject.arena[index].wait_e; unitSetting.waitMoveTurn = (OInt)jsonObject.arena[index].wait_m; unitSetting.waitExitTurn = (OInt)jsonObject.arena[index].wait_exit; unitSetting.startCtCalc = (eMapUnitCtCalcType)jsonObject.arena[index].ct_calc; unitSetting.startCtVal = (OInt)jsonObject.arena[index].ct_val; unitSetting.DisableFirceVoice = jsonObject.arena[index].fvoff != 0; unitSetting.side = (OInt)1; unitSetting.ai_pos.x = (OInt)jsonObject.arena[index].ai_x; unitSetting.ai_pos.y = (OInt)jsonObject.arena[index].ai_y; unitSetting.ai_len = (OInt)jsonObject.arena[index].ai_len; unitSetting.parent = (OString)jsonObject.arena[index].parent; if (jsonObject.arena[index].trg != null) { unitSetting.trigger = new EventTrigger(); unitSetting.trigger.Deserialize(jsonObject.arena[index].trg); } this.mArenaUnitSettings.Add(unitSetting); } } if (jsonObject.w_cond != null) { jsonObject.w_cond.CopyTo(this.mWinMonitorCondition); } if (jsonObject.l_cond != null) { jsonObject.l_cond.CopyTo(this.mLoseMonitorCondition); } if (jsonObject.gs != null) { this.mGimmickEvents = new List <JSON_GimmickEvent>((IEnumerable <JSON_GimmickEvent>)jsonObject.gs); } return(true); }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { switch (Network.ErrCode) { case Network.EErrCode.FirstChargeInvalid: this.OnBack(); break; case Network.EErrCode.FirstChargeNoLog: this.OnBack(); break; case Network.EErrCode.FirstChargeReceipt: this.OnBack(); break; case Network.EErrCode.FirstChargePast: this.OnBack(); break; default: this.OnRetry(); break; } } else { WebAPI.JSON_BodyResponse <FlowNode_ReqFirstChargeBonus.Json> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_ReqFirstChargeBonus.Json> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); if (jsonObject.body == null) { return; } ChargeInfoResultWindow component = (ChargeInfoResultWindow)((Component)this).get_gameObject().GetComponent <ChargeInfoResultWindow>(); if (UnityEngine.Object.op_Inequality((UnityEngine.Object)component, (UnityEngine.Object)null)) { List <FirstChargeReward> firstChargeRewardList = new List <FirstChargeReward>(); for (int index = 0; index < jsonObject.body.rewards.Length; ++index) { FirstChargeReward firstChargeReward = new FirstChargeReward(jsonObject.body.rewards[index]); if (firstChargeReward != null) { firstChargeRewardList.Add(firstChargeReward); } } if (firstChargeRewardList != null && firstChargeRewardList.Count > 0) { component.SetUp(firstChargeRewardList.ToArray()); } } this.Success(); } }
protected virtual Dictionary <string, GherkinLanguageSetting> ParseJsonContent(string languagesFileContent) { // ReSharper disable once InvokeAsExtensionMethod return(JSONParser.FromJson <Dictionary <string, GherkinLanguageSetting> >(languagesFileContent)); }
public void ARR01_empty_array_creation_works() { JSONParser jsParser = new JSONParser(); JSONArray jArr = (JSONArray)jsParser.FromJsonText("[]"); }
void CreateOperationOnCompleted(AsyncOperation obj) { if (m_CurrentRequest == null) { //If we lost our m_CurrentRequest request reference, we can't risk doing anything. return; } if (m_CurrentRequest.result != UnityWebRequest.Result.ProtocolError) { var jsonParser = new JSONParser(m_CurrentRequest.downloadHandler.text); var json = jsonParser.Parse(); var abort = false; try { var projectInfo = ExtractProjectInfoFromJson(json); try { ServicesRepository.DisableAllServices(shouldUpdateApiFlag: false); //Only register before creation. Remove first in case it was already added. //TODO: Review to avoid dependency on project refreshed UnityConnect.instance.ProjectStateChanged -= OnProjectStateChangedAfterCreation; UnityConnect.instance.ProjectStateChanged += OnProjectStateChangedAfterCreation; BindProject(projectInfo); } catch (Exception ex) { if (exceptionCallback != null) { exceptionCallback.Invoke(ex); abort = true; } else { //If there is no exception callback, we have to at least log it Debug.LogException(ex); } } if (!abort) { createButtonCallback?.Invoke(projectInfo); } } finally { m_CurrentRequest?.Dispose(); m_CurrentRequest = null; } } else if (m_CurrentRequest.responseCode == k_HttpStatusCodeUnprocessableEntity) { m_CurrentRequest?.Dispose(); m_CurrentRequest = null; m_CreateIteration++; RequestCreateOperation(); } else { try { var ex = new UnityConnectWebRequestException(L10n.Tr(k_CouldNotCreateProjectMessage)) { error = m_CurrentRequest.error, method = m_CurrentRequest.method, timeout = m_CurrentRequest.timeout, url = m_CurrentRequest.url, responseHeaders = m_CurrentRequest.GetResponseHeaders(), responseCode = m_CurrentRequest.responseCode, isHttpError = (m_CurrentRequest.result == UnityWebRequest.Result.ProtocolError), isNetworkError = (m_CurrentRequest.result == UnityWebRequest.Result.ConnectionError), }; if (exceptionCallback != null) { exceptionCallback.Invoke(ex); } else { //If there is no exception callback, we have to at least log it Debug.LogException(ex); } } finally { m_CurrentRequest?.Dispose(); m_CurrentRequest = null; } } }
/// <summary> /// Parse a string into a JSONObject /// </summary> /// <param name="toParse">The string (document) to be parsed</param> /// <returns>A JSONObject representing the JSON document</returns> public static JSONObject Parse(string toParse) { return(JSONParser.ParseJSON(toParse)); }
public static JSON ParseString(string data) { JSONParser parse = new JSONParser(data); return new JSON(parse.ParseValue()); }
public override async Task <LocationQueryViewModel> GetLocation(string query) { LocationQueryViewModel location = null; string queryAPI = "https://autocomplete.wunderground.com/aq?query="; string options = "&h=0&cities=1"; Uri queryURL = new Uri(queryAPI + query + options); OpenWeather.AC_RESULT result; WeatherException wEx = null; try { // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // End Stream webClient.Dispose(); // Load data var root = JSONParser.Deserializer <OpenWeather.AC_Rootobject>(contentStream); result = root.RESULTS.FirstOrDefault(); // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { result = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); } #endif Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting location"); } if (result != null && !String.IsNullOrWhiteSpace(result.l)) { location = new LocationQueryViewModel(result); } else { location = new LocationQueryViewModel(); } return(location); }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { this._Failed(); } else { DebugMenu.Log("API", "homeapi:{" + www.text + "}"); WebAPI.JSON_BodyResponse <FlowNode_HomeApi.JSON_HomeApiResponse> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_HomeApi.JSON_HomeApiResponse> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); if (jsonObject.body != null && jsonObject.body.player != null) { MonoSingleton <GameManager> .Instance.Player.ValidGpsGift = jsonObject.body.player.areamail_enabled != 0; MonoSingleton <GameManager> .Instance.Player.ValidFriendPresent = jsonObject.body.player.present_granted != 0; MultiInvitationReceiveWindow.SetBadge(jsonObject.body.player.multi_inv != 0); MonoSingleton <GameManager> .Instance.Player.FirstChargeStatus = jsonObject.body.player.charge_bonus; } else { MonoSingleton <GameManager> .Instance.Player.ValidGpsGift = false; MonoSingleton <GameManager> .Instance.Player.ValidFriendPresent = false; MultiInvitationReceiveWindow.SetBadge(false); MonoSingleton <GameManager> .Instance.Player.FirstChargeStatus = 0; } if (jsonObject.body != null && jsonObject.body.pubinfo != null) { LoginNewsInfo.SetPubInfo(jsonObject.body.pubinfo); } this._Success(); } }
public override async Task <ObservableCollection <LocationQueryViewModel> > GetLocations(string query) { ObservableCollection <LocationQueryViewModel> locations = null; string queryAPI = "https://autocomplete.wunderground.com/aq?query="; string options = "&h=0&cities=1"; Uri queryURL = new Uri(queryAPI + query + options); // Limit amount of results shown int maxResults = 10; try { // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // End Stream webClient.Dispose(); // Load data locations = new ObservableCollection <LocationQueryViewModel>(); var root = JSONParser.Deserializer <OpenWeather.AC_Rootobject>(contentStream); foreach (OpenWeather.AC_RESULT result in root.RESULTS) { // Filter: only store city results if (result.type != "city") { continue; } locations.Add(new LocationQueryViewModel(result)); // Limit amount of results maxResults--; if (maxResults <= 0) { break; } } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { locations = new ObservableCollection <LocationQueryViewModel>(); Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting locations"); } if (locations == null || locations.Count == 0) { locations = new ObservableCollection <LocationQueryViewModel>() { new LocationQueryViewModel() } } ; return(locations); }
/// <summary> /// fetches the JSON data from a server /// </summary> private IEnumerator LoadJSONBookData(string jsonBookUrl) { // Gets the full book json url string fullBookURL = JsonServerUrl + jsonBookUrl; // Gets the json book info from the url mJsonBookInfo = new WWW(fullBookURL); yield return mJsonBookInfo; // Loading done mIsLoadingBookData = false; if (mJsonBookInfo.error == null) { // Parses the json Object JSONParser parser = new JSONParser(); BookData bookData = parser.ParseString(mJsonBookInfo.text); mBookData = bookData; // Updates the BookData info in the augmented object mBookInformationParser.UpdateBookData(bookData); mIsLoadingBookThumb = true; } else { //Debug.LogError("Error downloading json"); BookData bookData = new BookData(); bookData.SetBookTitle("The Hunger Game"); bookData.SetBookAuthor("Suzanne Collins"); bookData.SetBookRating(4); bookData.SetBookOverallRating(23933); bookData.SetBookRegularPrice(10.99f); bookData.SetBookYourPrice(7.09f); bookData.SetBookThumbUrl("http://ecx.images-amazon.com/images/I/41bOj-am1RL._SX331_BO1,204,203,200_.jpg"); bookData.SetBookDetailUrl("http://www.amazon.com/The-Hunger-Games-Book-1/dp/0439023521/ref=pd_bxgy_14_img_z"); mBookData = bookData; Debug.Log("mBookData assigned"); // Updates the BookData info in the augmented object mBookInformationParser.UpdateBookData(bookData); mIsLoadingBookThumb = true; } }
public override void OnSuccess(WWWResult www) { if (TowerErrorHandle.Error((FlowNode_Network)this)) { return; } TowerResuponse towerResuponse = MonoSingleton <GameManager> .Instance.TowerResuponse; WebAPI.JSON_BodyResponse <ReqTowerRank.JSON_TowerRankResponse> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <ReqTowerRank.JSON_TowerRankResponse> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); towerResuponse.Deserialize(jsonObject.body); this.Success(); }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { this.OnRetry(); } else { WebAPI.JSON_BodyResponse <FlowNode_ReqLoginPack.JSON_ReqLoginPackResponse> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_ReqLoginPack.JSON_ReqLoginPackResponse> >(www.text); if (jsonObject.body == null) { this.OnRetry(); } else { GameManager instance = MonoSingleton <GameManager> .Instance; instance.ResetJigenQuests(); if (!instance.Deserialize(jsonObject.body.quests)) { this.OnFailed(); } else { this.reflectTrophyProgs(jsonObject.body.trophyprogs); this.reflectTrophyProgs(jsonObject.body.bingoprogs); this.reflectLoginTrophyProgs(); GlobalVars.CurrentChatChannel.Set(jsonObject.body.channel); GlobalVars.SelectedSupportUnitUniqueID.Set(jsonObject.body.support); Network.RemoveAPI(); this.Success(); } } } }
void GetBuildTargetsRequestOnCompleted(AsyncOperation obj) { if (m_Provider.m_GetProjectBuildTargetsRequest == null) { //If we lost our request reference, we can't risk doing anything. return; } try { if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(m_Provider.m_GetProjectBuildTargetsRequest)) { try { var jsonParser = new JSONParser(m_Provider.m_GetProjectBuildTargetsRequest.downloadHandler.text); var json = jsonParser.Parse(); var buildEntryList = json.AsList(); if (buildEntryList.Count <= 0) { CloudBuildPoller.instance.Disable(); } else { m_Provider.rootVisualElement.Q(k_NoTargetContainer).style.display = DisplayStyle.None; m_Provider.rootVisualElement.Q(k_AddTargetButton).style.display = DisplayStyle.None; m_Provider.rootVisualElement.Q(k_ManageTargetButton).style.display = DisplayStyle.Flex; m_Provider.rootVisualElement.Q(k_PollFooterName).style.display = DisplayStyle.Flex; m_Provider.rootVisualElement.Q(k_PollFooterSectionName).style.display = DisplayStyle.Flex; var pollerToggle = m_Provider.rootVisualElement.Q <Toggle>(k_PollToggleName); if (!CloudBuildPoller.instance.enabledOnce) { CloudBuildPoller.instance.Enable(m_CloudBuildApiOrgLatestBuilds); } pollerToggle.SetValueWithoutNotify(CloudBuildPoller.instance.enabled); pollerToggle.RegisterValueChangedCallback(evt => { if (evt.newValue) { CloudBuildPoller.instance.Enable(m_CloudBuildApiOrgLatestBuilds); } else { CloudBuildPoller.instance.Disable(); } }); m_Provider.rootVisualElement.Q <TextElement>(className: k_ServiceTargetContainerTitleClassName).text = L10n.Tr(k_LabelConfiguredTargets); var targetsContainer = m_Provider.rootVisualElement.Q(className: k_ServiceTargetContainerClassName); foreach (var jsonBuildEntry in buildEntryList) { var buildEntry = jsonBuildEntry.AsDict(); AddBuildTarget(targetsContainer, buildEntry); } } m_Provider.rootVisualElement.Q(className: k_ServiceCloudBuildContainerClassName).style.display = DisplayStyle.Flex; m_Provider.rootVisualElement.Q(className: k_ServiceCloudProgressClassName).style.display = DisplayStyle.None; } catch (Exception ex) { NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, L10n.Tr(k_MessageErrorForProjectBuildTargetsData)); Debug.LogException(ex); } } } finally { m_Provider.m_GetProjectBuildTargetsRequest.Dispose(); m_Provider.m_GetProjectBuildTargetsRequest = null; } }
public void setProblem(JSONParser _problem) { problem = _problem; }
void AddBuildTarget(VisualElement targetsContainer, Dictionary <string, JSONValue> buildEntry) { if (buildEntry[k_JsonNodeNameEnabled].AsBool()) { ServicesConfiguration.instance.RequestCloudBuildApiUrl(cloudBuildApiUrl => { var buildTargetName = buildEntry[k_JsonNodeNameName].AsString(); var buildTargetId = buildEntry[k_JsonNodeNameBuildTargetId].AsString(); var buildTargetUrls = buildEntry[k_JsonNodeNameLinks].AsDict(); var startBuildUrl = cloudBuildApiUrl + buildTargetUrls[k_JsonNodeNameStartBuilds].AsDict()[k_JsonNodeNameHref].AsString(); var targetContainer = new VisualElement(); targetContainer.AddToClassList(k_ClassNameTargetEntry); var buildNameTextElement = new TextElement(); buildNameTextElement.AddToClassList(k_ClassNameTitle); buildNameTextElement.text = buildTargetName; targetContainer.Add(buildNameTextElement); var buildButton = new Button(); buildButton.name = k_BuildButtonNamePrefix + buildTargetId; buildButton.AddToClassList(k_ClassNameBuildButton); if (m_BillingPlanLabel.ToLower() == k_SubscriptionPersonal || k_SubscriptionTeamsBasic.ToLower() == k_SubscriptionPersonal) { buildButton.SetEnabled(false); } buildButton.text = L10n.Tr(k_LabelBuildButton); buildButton.clicked += () => { var uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(k_LaunchBuildPayload)); var launchBuildPostRequest = new UnityWebRequest(startBuildUrl, UnityWebRequest.kHttpVerbPOST) { downloadHandler = new DownloadHandlerBuffer(), uploadHandler = uploadHandler }; launchBuildPostRequest.suppressErrorsToConsole = true; launchBuildPostRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}"); launchBuildPostRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); m_Provider.m_BuildRequests.Add(launchBuildPostRequest); var launchingMessage = string.Format(L10n.Tr(k_MessageLaunchingBuild), buildTargetName); Debug.Log(launchingMessage); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Info, launchingMessage); EditorAnalytics.SendLaunchCloudBuildEvent(new BuildPostInfo() { targetName = buildTargetName }); var operation = launchBuildPostRequest.SendWebRequest(); operation.completed += asyncOperation => { try { if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(launchBuildPostRequest)) { try { if (launchBuildPostRequest.responseCode == k_HttpResponseCodeAccepted) { var jsonLaunchedBuildParser = new JSONParser(launchBuildPostRequest.downloadHandler.text); var launchedBuildJson = jsonLaunchedBuildParser.Parse(); var launchedBuilds = launchedBuildJson.AsList(); foreach (var rawLaunchedBuild in launchedBuilds) { var launchedBuild = rawLaunchedBuild.AsDict(); if (launchedBuild.ContainsKey(k_JsonNodeNameBuild)) { var buildNumber = launchedBuild[k_JsonNodeNameBuild].AsFloat().ToString(); var message = string.Format(L10n.Tr(k_MessageLaunchedBuildSuccess), buildNumber, buildTargetName); Debug.Log(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Info, message); } else if (launchedBuild.ContainsKey(k_JsonNodeNameError)) { var message = string.Format(L10n.Tr(k_MessageLaunchedBuildFailedWithMsg), buildTargetName, launchedBuild[k_JsonNodeNameError].ToString()); Debug.LogError(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, message); } } } else { var message = L10n.Tr(k_MessageLaunchedBuildFailure); Debug.LogError(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, message); } } catch (Exception ex) { NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, L10n.Tr(k_MessageErrorForBuildLaunch)); Debug.LogException(ex); } } } finally { m_Provider.m_BuildRequests.Remove(launchBuildPostRequest); launchBuildPostRequest.Dispose(); launchBuildPostRequest = null; } }; }; targetContainer.Add(buildButton); targetsContainer.Add(targetContainer); var separator = new VisualElement(); separator.AddToClassList(k_ClassNameSeparator); targetsContainer.Add(separator); }); } }
void Update() { if (m_Timer.DoTick()) { var getCurrentBuildTargetStatusRequest = new UnityWebRequest(m_PollingUrl, UnityWebRequest.kHttpVerbGET) { downloadHandler = new DownloadHandlerBuffer() }; getCurrentBuildTargetStatusRequest.suppressErrorsToConsole = true; getCurrentBuildTargetStatusRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}"); var operation = getCurrentBuildTargetStatusRequest.SendWebRequest(); operation.completed += asyncOperation => { try { if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(getCurrentBuildTargetStatusRequest)) { try { var jsonParser = new JSONParser(getCurrentBuildTargetStatusRequest.downloadHandler.text); var json = jsonParser.Parse(); var buildList = json.AsList(); var trackedBuilds = new List <string>(m_BuildsToReportOn); if (buildList.Count > 0) { foreach (var rawBuild in buildList) { var build = rawBuild.AsDict(); var buildNumber = build[k_JsonNodeNameBuild].AsFloat().ToString(); var buildId = build[k_JsonNodeNameBuildTargetId].AsString() + "_" + buildNumber; var buildStatus = build[k_JsonNodeNameBuildStatus].AsString().ToLower(); if (trackedBuilds.Contains(buildId)) { trackedBuilds.Remove(buildId); } if (m_BuildsToReportOn.Contains(buildId) && (k_BuildStatusCanceled.Equals(buildStatus) || k_BuildStatusFailure.Equals(buildStatus) || k_BuildStatusSuccess.Equals(buildStatus) || k_BuildStatusUnknown.Equals(buildStatus) ) ) { if (!k_BuildStatusStarted.Equals(buildStatus) && !k_BuildStatusUnknown.Equals(buildStatus)) { m_BuildsToReportOn.Remove(buildId); } var buildTargetName = build[k_JsonNodeNameBuildTargetName].AsString(); var severity = Notification.Severity.Info; var message = string.Empty; switch (buildStatus) { case k_BuildStatusCanceled: severity = Notification.Severity.Warning; message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusCanceled); Debug.LogWarning(message); break; case k_BuildStatusFailure: severity = Notification.Severity.Error; message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusFailure); Debug.LogError(message); break; case k_BuildStatusStarted: message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusStartedMessage); Debug.Log(message); break; case k_BuildStatusSuccess: message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusSuccess); Debug.Log(message); break; case k_BuildStatusUnknown: message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusUnknown); Debug.LogWarning(message); break; } NotificationManager.instance.Publish(Notification.Topic.BuildService, severity, message); } else if (!m_BuildsToReportOn.Contains(buildId) && (k_BuildStatusQueued.Equals(buildStatus) || k_BuildStatusStarted.Equals(buildStatus) || k_BuildStatusSentToBuilder.Equals(buildStatus) || k_BuildStatusSentRestarted.Equals(buildStatus) ) ) { if (k_BuildStatusSentRestarted.Equals(buildStatus)) { var buildTargetName = build[k_JsonNodeNameBuildTargetName].AsString(); var message = string.Format(L10n.Tr(k_BuildFinishedWithStatusMsg), buildNumber, buildTargetName, k_BuildStatusSentRestarted); Debug.Log(message); NotificationManager.instance.Publish(Notification.Topic.BuildService, Notification.Severity.Info, message); } m_BuildsToReportOn.Add(buildId); } } //If a build vanishes, we don't want to keep investigating it foreach (var missingTrackedBuild in trackedBuilds) { m_BuildsToReportOn.Remove(missingTrackedBuild); } } } catch (Exception ex) { NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, L10n.Tr(k_MessageErrorForApiStatusData)); Debug.LogException(ex); } } } finally { getCurrentBuildTargetStatusRequest.Dispose(); } }; } }
void GetApiStatusRequestOnCompleted(AsyncOperation obj) { if (m_Provider.m_GetApiStatusRequest == null) { //If we lost our request reference, we can't risk doing anything. return; } try { if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(m_Provider.m_GetApiStatusRequest)) { try { var jsonParser = new JSONParser(m_Provider.m_GetApiStatusRequest.downloadHandler.text); var json = jsonParser.Parse(); var notificationEntryList = json.AsList(); if (notificationEntryList.Count > 0) { foreach (var jsonNotificationEntry in notificationEntryList) { var notificationEntry = jsonNotificationEntry.AsDict(); var notificationText = notificationEntry[k_JsonNodeNameText].AsString(); var billingPlan = string.Empty; if (notificationEntry.ContainsKey(k_JsonNodeNameBillingPlan)) { billingPlan = notificationEntry[k_JsonNodeNameBillingPlan].AsString(); } var notificationAlertType = notificationEntry[k_JsonNodeNameAlertType].AsString().ToLower(); if (string.IsNullOrEmpty(billingPlan) || m_BillingPlanLabel.ToLower().Equals(billingPlan.ToLower())) { var severity = Notification.Severity.Error; if (notificationAlertType.Equals(Notification.Severity.Warning.ToString().ToLower())) { severity = Notification.Severity.Warning; } else if (notificationAlertType.Equals(Notification.Severity.Info.ToString().ToLower())) { severity = Notification.Severity.Info; } NotificationManager.instance.Publish(Notification.Topic.BuildService, severity, notificationText); } } } } catch (Exception ex) { NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, L10n.Tr(k_MessageErrorForApiStatusData)); Debug.LogException(ex); } } } finally { m_Provider.m_GetApiStatusRequest.Dispose(); m_Provider.m_GetApiStatusRequest = null; } }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { switch (Network.ErrCode) { case Network.EErrCode.NoDevice: case Network.EErrCode.Authorize: this.OnFailed(); return; } } WebAPI.JSON_BodyResponse <FlowNode_GetAccessToken.JSON_AccessToken> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_GetAccessToken.JSON_AccessToken> >(www.text); if (jsonObject.body == null) { this.OnFailed(); } else { if (jsonObject.body.access_token == null && jsonObject.body.status != null) { GlobalVars.BanStatus = int.Parse(jsonObject.body.status); GlobalVars.CustomerID = jsonObject.body.cuid; Network.RemoveAPI(); this.ActivateOutputLinks(3); } else { if (jsonObject.body.device_id != null) { MonoSingleton <GameManager> .Instance.SaveAuth(jsonObject.body.device_id); } Network.SessionID = jsonObject.body.access_token; Network.RemoveAPI(); if (jsonObject.body.old_device_id != null) { MonoSingleton <GameManager> .Instance.SaveAuth(jsonObject.body.old_device_id, jsonObject.body.secret_key); MonoSingleton <GameManager> .Instance.InitAuth(); this.ActivateOutputLinks(2); } else { this.ActivateOutputLinks(1); } } ((Behaviour)this).set_enabled(false); } }
public override void OnSuccess(WWWResult www) { if (Network.IsError) { Network.EErrCode errCode = Network.ErrCode; this.OnRetry(); } else { WebAPI.JSON_BodyResponse <FlowNode_ReqConceptCardMaterialMix.Json_ConceptCardMaterialDataMix> jsonObject = JSONParser.parseJSONObject <WebAPI.JSON_BodyResponse <FlowNode_ReqConceptCardMaterialMix.Json_ConceptCardMaterialDataMix> >(www.text); DebugUtility.Assert(jsonObject != null, "res == null"); Network.RemoveAPI(); long iid = -1; int beforeLevel = -1; int beforeAwakeCount = -1; int beforeTrust = -1; if (jsonObject.body.concept_card != null) { iid = jsonObject.body.concept_card.iid; ConceptCardData conceptCardByUniqueId = MonoSingleton <GameManager> .Instance.Player.FindConceptCardByUniqueID(iid); if (conceptCardByUniqueId != null) { beforeLevel = (int)conceptCardByUniqueId.Lv; beforeAwakeCount = (int)conceptCardByUniqueId.AwakeCount; beforeTrust = (int)conceptCardByUniqueId.Trust; } } try { MonoSingleton <GameManager> .Instance.Deserialize(jsonObject.body.player); MonoSingleton <GameManager> .Instance.Player.Deserialize(jsonObject.body.concept_card); MonoSingleton <GameManager> .Instance.Player.OverWriteConceptCardMaterials(jsonObject.body.materials); } catch (Exception ex) { DebugUtility.LogException(ex); return; } MonoSingleton <GameManager> .Instance.Player.OnGoldChange(this.totalMixZeny); MonoSingleton <GameManager> .Instance.ServerSyncTrophyExecEnd(www); ConceptCardData conceptCardByUniqueId1 = MonoSingleton <GameManager> .Instance.Player.FindConceptCardByUniqueID(iid); MonoSingleton <GameManager> .Instance.Player.OnMixedConceptCard(jsonObject.body.concept_card.iname, beforeLevel, (int)conceptCardByUniqueId1.Lv, beforeAwakeCount, (int)conceptCardByUniqueId1.AwakeCount, beforeTrust, (int)conceptCardByUniqueId1.Trust); this.ActivateOutputLinks(1000); ((Behaviour)this).set_enabled(false); } }
// ================================================================================================================ // INTERNAL INTERFACE --------------------------------------------------------------------------------------------- protected override void parseValueFromInput() { ParsingState parsingState = ParsingState.Start; char c; int i = 0; string key = "undefined"; JSONValue valueObject; value = new Dictionary <string, object>(); while (i < input.Length && parsingState != ParsingState.End) { c = input.ToString(inputStart + i, 1)[0]; // TODO: is this efficient? switch (parsingState) { case ParsingState.Start: if (c == CHAR_START) { // Starting object parsingState = ParsingState.BeforeKey; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key start"); } break; case ParsingState.BeforeKey: if (!JSONParser.isWhitespace(c)) { if (JSONString.matchesInput(input, inputStart + i)) { // Key starting JSONString keyObject = new JSONString(input, inputStart + i); key = (string)keyObject.getValue(); i += keyObject.getInputLength() - 1; parsingState = ParsingState.AfterKey; } else if (c == CHAR_END) { // Premature end parsingState = ParsingState.End; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key name"); } } break; case ParsingState.AfterKey: if (!JSONParser.isWhitespace(c)) { if (c == CHAR_KEY_SEPARATOR) { parsingState = ParsingState.BeforeValue; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key separator"); } } break; case ParsingState.BeforeValue: if (!JSONParser.isWhitespace(c)) { valueObject = JSONParser.parse(input, inputStart + i); i += valueObject.getInputLength() - 1; value.Add(key, valueObject.getValue()); parsingState = ParsingState.AfterValue; } break; case ParsingState.AfterValue: if (!JSONParser.isWhitespace(c)) { if (c == CHAR_END) { parsingState = ParsingState.End; } else if (c == CHAR_ITEM_SEPARATOR) { parsingState = ParsingState.BeforeKey; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key end"); } } break; } i++; } inputLength = i; }
void LoadTable(JSONParser json) { LogMessage += "MTC line 160\n"; canvas.name = "Table Canvas"; data = json.result.data; variables = json.result.variables; cols = variables.Length + 1; // num of vars, also data[0][0].Length rows = data[0].Length; // num of data points LogMessage += "Cols: " + cols + " Rows: " + rows + "\n"; textArray = new GameObject[rows, cols]; varArray = new GameObject[1, cols]; variableColor = new Color(247, 123, 85, 255); canvas.GetComponent <RectTransform>().sizeDelta = new Vector2(startX * 2 + xDiff * (cols + 1), yDiff * rows); canvas.GetComponent <Canvas>().renderMode = RenderMode.ScreenSpaceOverlay; panel = new GameObject(); panel.transform.SetParent(canvas.transform); panel.AddComponent <RectTransform>(); float xDelta = startX + (xDiff * (cols)) / 2; //Debug.Log("X" + xDelta); float yDelta = (yDiff * (rows + 1)) / 2; //Debug.Log("Y" + yDelta); panel.GetComponent <RectTransform>().sizeDelta = new Vector2(xDelta * 2, yDelta * 2); startY = panel.GetComponent <RectTransform>().rect.height; panel.name = "Table Panel"; panel.transform.position = canvas.GetComponent <RectTransform>().position; float widthScale = parentCanvas.GetComponent <RectTransform>().rect.width / panel.GetComponent <RectTransform>().rect.width; float heightScale = 1050.0f / panel.GetComponent <RectTransform>().rect.height; Debug.Log("height is " + panel.GetComponent <RectTransform>().rect.height); float scale; if (widthScale < heightScale) { scale = widthScale; } else { scale = heightScale; } panel.GetComponent <RectTransform>().localScale = new Vector3(scale, scale, 1); LogMessage += "MTC line 190\n"; // making variables and variable buttons for (int i = 0; i < variables.Length; i++) { Color normalColor = new Color(0.130f, 0.130f, 0.150f, 1); Color pressedColor = new Color(0.224f, 0.235f, 0.274f, 1); GameObject newObj = new GameObject(); GameObject textObj = new GameObject(); newObj.transform.SetParent(panel.transform); newObj.name = variables[i]; newObj.AddComponent <RectTransform>(); newObj.GetComponent <RectTransform>().sizeDelta = new Vector2(200, 120); newObj.GetComponent <RectTransform>().localScale = new Vector3(scale, scale, 1); textObj.AddComponent <RectTransform>(); textObj.GetComponent <RectTransform>().sizeDelta = new Vector2(200, 120); Button varButton = newObj.AddComponent <Button>(); Image buttonImage = newObj.AddComponent <Image>(); buttonImage.color = new Color(1f, 1f, 1f, 1f); buttonImage.sprite = Resources.Load <Sprite>("unity_builtin_extra/UISprite"); varButton.image = buttonImage; ColorBlock cb = varButton.colors; cb.normalColor = normalColor; cb.pressedColor = pressedColor; cb.highlightedColor = normalColor; cb.colorMultiplier = 1; cb.fadeDuration = 0.1f; varButton.colors = cb; varButton.onClick.AddListener(buttonAppend.ButtonTrigger); textArray[0, i] = newObj; varArray[0, i] = newObj; textObj.transform.SetParent(newObj.transform); textObj.GetComponent <RectTransform>().localScale = new Vector3(scale, scale, 1); Text myText = textObj.AddComponent <Text>(); myText.text = variables[i]; myText.fontSize = 91; myText.font = font; myText.alignment = TextAnchor.MiddleCenter; myText.color = Color.gray;//variableColor; textArray[0, i].transform.localPosition = new Vector3(startX + (xDiff * i) - xDelta, startY + yDiff - yDelta, 0); Navigation customNav = new Navigation(); customNav.mode = Navigation.Mode.Automatic; varButton.navigation = customNav; } LogMessage += "MTC line 237\n"; // results GameObject obj = new GameObject(); obj.transform.SetParent(panel.transform); obj.name = "result"; obj.AddComponent <RectTransform>(); obj.GetComponent <RectTransform>().sizeDelta = new Vector2(400, 225); obj.GetComponent <RectTransform>().localScale = new Vector3(scale, scale, 1); textArray[0, variables.Length] = obj; varArray[0, variables.Length] = obj; Text text = obj.AddComponent <Text>(); text.text = "result"; text.fontSize = 85; text.font = font; text.color = Color.gray;// variableColor; text.alignment = TextAnchor.MiddleCenter; textArray[0, variables.Length].transform.localPosition = new Vector3(startX + (xDiff * variables.Length) - xDelta, startY + yDiff - yDelta, 0); // creating table for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { GameObject newObj = new GameObject(); newObj.transform.SetParent(panel.transform); newObj.name = "(" + i + ", " + j + ")"; newObj.AddComponent <RectTransform>(); newObj.GetComponent <RectTransform>().sizeDelta = new Vector2(400, 225); newObj.GetComponent <RectTransform>().localScale = new Vector3(scale, scale, 1); textArray[i, j] = newObj; Text myText = newObj.AddComponent <Text>(); if (j == cols - 1) { var engine = new Engine(); for (int k = 0; k < cols - 1; k++) { engine.SetValue(variables[k], data[0][i][k]); } try { //Debug.Log(GetInputExpression.exp); engine.Execute(GetInputExpression.exp); myText.text = ((double)engine.GetCompletionValue().ToObject()).ToString("G4"); } catch (Exception err) { Debug.Log(err.Message); myText.text = ""; } } else { myText.text = data[0][i][j].ToString(); } myText.fontSize = 91; myText.font = font; myText.alignment = TextAnchor.MiddleCenter; textArray[i, j].transform.localPosition = new Vector3(startX + (xDiff * j) - xDelta, startY - (yDiff * i) - yDelta, 0); } } canvas.GetComponent <CanvasScaler>().uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; canvas.GetComponent <CanvasScaler>().referenceResolution = new Vector2(1440, 2560); variableJSON = "{"; for (int x = 0; x < cols - 1; x++) { variableJSON += "\"" + varArray[0, x].name + "\":\"int\","; } variableJSON = variableJSON.Substring(0, variableJSON.Length - 1); variableJSON += '}'; LogMessage += "VariableJson" + variableJSON + "\n"; }
void LoadProjectField(string organizationName, PopupField <string> projectIdField) { ServicesConfiguration.instance.RequestOrganizationProjectsApiUrl(m_OrgIdByName[organizationName], organizationProjectsApiUrl => { var getProjectsRequest = new UnityWebRequest(organizationProjectsApiUrl, UnityWebRequest.kHttpVerbGET) { downloadHandler = new DownloadHandlerBuffer() }; getProjectsRequest.suppressErrorsToConsole = true; getProjectsRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}"); var operation = getProjectsRequest.SendWebRequest(); operation.completed += op => { try { if (getProjectsRequest.result != UnityWebRequest.Result.ProtocolError) { var jsonParser = new JSONParser(getProjectsRequest.downloadHandler.text); var json = jsonParser.Parse(); try { m_ProjectInfoByName = new Dictionary <string, ProjectInfoData>(); var jsonProjects = json.AsDict()[k_JsonProjectsNodeName].AsList(); foreach (var jsonProject in jsonProjects) { if (!jsonProject.AsDict()[k_JsonArchivedNodeName].AsBool()) { var projectInfo = ExtractProjectInfoFromJson(jsonProject); m_ProjectInfoByName.Add(projectInfo.name, projectInfo); } } var projectNames = new List <string> { L10n.Tr(k_SelectProjectText) }; var sortedProjectNames = new List <string>(m_ProjectInfoByName.Keys); sortedProjectNames.Sort(); projectNames.AddRange(sortedProjectNames); projectIdField.choices = projectNames; projectIdField.SetEnabled(true); } catch (Exception ex) { if (exceptionCallback != null) { exceptionCallback.Invoke(ex); } else { //If there is no exception callback, we have to at least log it Debug.LogException(ex); } } } else { var ex = new UnityConnectWebRequestException(L10n.Tr(k_CouldNotObtainProjectMessage)) { error = getProjectsRequest.error, method = getProjectsRequest.method, timeout = getProjectsRequest.timeout, url = getProjectsRequest.url, responseHeaders = getProjectsRequest.GetResponseHeaders(), responseCode = getProjectsRequest.responseCode, isHttpError = (getProjectsRequest.result == UnityWebRequest.Result.ProtocolError), isNetworkError = (getProjectsRequest.result == UnityWebRequest.Result.ConnectionError), }; if (exceptionCallback != null) { exceptionCallback.Invoke(ex); } else { //If there is no exception callback, we have to at least log it Debug.LogException(ex); } } } finally { getProjectsRequest.Dispose(); } }; }); }
// Update is called once per frame void Update() { //Debug.Log("Counter from Table: " +counter); //SinglePlayer case /*if (SceneManager.Equals(SceneManager.GetActiveScene(), "SinglePlayer")) * { * if (counter == 3) * { * displaySingleScore(); * } * } * else * { * if (Time.time - startTime > 15) * { * displayMultiScore(); * } * }*/ if (Time.time - startTime > timeLimit && SpaghettiGameManager.counter > 0) { if (Time.time - startTime > (timeLimit + 10)) { canvas.SetActive(true); MultiplayerEnter.acceptedInv.Clear(); scoreCanvas.SetActive(false); ClearTable(); GameObject.Destroy(panel); SpaghettiGameManager.counter = 0; startTime = Time.time; UpdateInv.Inv = "Invariants\n"; currentJson = CallServer.ExecuteServerCall(); json = new JSONParser(currentJson); LoadTable(json); } else { feedbackBox.GetComponent <Text>().text = ""; canvas.SetActive(false); scoreCanvas.SetActive(true); Text scoreText = scoreDisplay.GetComponent <Text>(); scoreText.text = "Your score: " + score + "\nYour Opponent: " + opponent; } } for (int i = 0; i < rows; i++) { var engine = new Engine(); for (int k = 0; k < cols - 1; k++) { engine.SetValue(variables[k], data[0][i][k]); } try { if (GetInputExpression.exp.Length == 0) { textArray[i, cols - 1].GetComponent <Text>().text = ""; //numbers.Clear(); } else { //Debug.Log(GetInputExpression.exp); engine.Execute(GetInputExpression.exp); //Debug.Log(engine.GetCompletionValue().ToObject()); textArray[i, cols - 1].GetComponent <Text>().text = (engine.GetCompletionValue().ToObject()).ToString(); float test = 0; if (float.TryParse(textArray[i, cols - 1].GetComponent <Text>().text, out test)) { textArray[i, cols - 1].GetComponent <Text>().text = test.ToString("G4"); } } } catch (Exception err) { // Debug.Log(err.Message); } } }
//--------------------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------------------- public JSONInStream (string input) { JSONParser parser = new JSONParser(); node = parser.Parse(new FlashCompatibleTextReader(input)); }
/// <summary> /// Load current soldier information /// </summary> public ISoldier Load() { var parser = new JSONParser(); return parser.Parse(); }