public void GivenIHaveParsedAJSONSchoolFile() { _jsonParser = new JsonObjectParser(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(Resources.SchoolJson))) { Json.Parse(_jsonParser, stream, "blackboard"); } }
/// <summary> /// 验证用户登录 /// </summary> /// <param name="userName">用户名</param> /// <param name="userPass">密码</param> /// <returns></returns> public Task<User> AuthanticateUser(string userName,string userPass) { var request = new RestRequest("Authentication"); var passMD5 = MD5Core.GetHashString(userPass).ToLowerInvariant(); request.AddHeader("UserName", userName); request.AddHeader("Key", HMACSHAEncryptor.GetHASMString(passMD5)); var taskCompletionSource=new TaskCompletionSource<User>(); User user = null; AppClient.ExecuteAsyncGet(request,(response,e)=>{ if(response.StatusCode==HttpStatusCode.OK) { response.ContentEncoding = "utf-8"; var resultJson = response.Content; JObject jObject = JObject.Parse(resultJson); var loginResult =int.Parse(jObject["Result"].ToString()); if (loginResult > 0) { user = new JsonParser().Deserialize<User>(resultJson); } } taskCompletionSource.TrySetResult(user); },"Get"); return taskCompletionSource.Task; }
internal string DeserializeJobSubmissionResponse(string payload) { var ret = UnknownJobId; using (var parser = new JsonParser(payload)) { var respObj = parser.ParseNext(); if (respObj == null || respObj.IsError || respObj.IsNullOrMissing || !respObj.IsObject) { throw new SerializationException(respObj.ToString()); } var jobId = this.GetJsonPropertyStringValue(respObj, JobId); if (string.IsNullOrEmpty(jobId)) { var errorString = this.GetJsonPropertyStringValue(respObj, ErrorString); if (!string.IsNullOrEmpty(errorString)) { throw new InvalidOperationException(errorString); } throw new InvalidOperationException(); } ret = jobId; } return ret; }
public void JsonNameParseTest() { var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); var parser = new JsonParser(settings); // It is safe to use either original field name or explicitly specified json_name Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); }
public void should_deserialize_json() { var parser = new JsonParser(); var result = parser.Parse<RootObject>(json); Assert.That(result, Is.Not.Null); Assert.That(result.Store.StoreName, Is.EqualTo("HHV")); }
public void SimpleObjectDeserialize() { var parser = new JsonParser(singleLineJson); var rlt = parser.Parse(); if (rlt.success) { var d = rlt.Get<Dobj>(); var j = Dobj.ToJson(d); var s = "{ \"config\":{ \"boolval\":True,\"numval\":20.1,\"oval\":{ \"result\":\"pass\" },\"aval\":[1,True,\"text\",{ \"key\":\"val\" },[1.0,2.0,3.0]] } }"; Assert.AreEqual(s, j); } Assert.AreEqual(true, rlt.success); }
internal JobList DeserializeListJobResult(string payload) { var ret = new JobList(); var list = new List<JobDetails>(); using (var parser = new JsonParser(payload)) { var jobList = parser.ParseNext(); if (jobList == null || !jobList.IsValidArray()) { throw new InvalidOperationException(); } if (jobList.IsEmpty) { return ret; } for (var i = 0; i < jobList.Count(); i++) { var job = jobList.GetIndex(i); if (job == null || !job.IsValidObject()) { continue; } var detailProp = job.GetProperty(DetailPropertyName); if (detailProp != null && detailProp.IsValidObject()) { try { var jobDetails = this.DeserializeJobDetails((JsonObject)detailProp); jobDetails.SubmissionTime = jobDetails.SubmissionTime.ToLocalTime(); if (jobDetails != null) { list.Add(jobDetails); } } catch (InvalidOperationException) { //Eat it. } } } } ret.Jobs.AddRange((from j in list orderby j.SubmissionTime.ToUniversalTime() select j)); return ret; }
public void ParseSimpleJson() { var str = TestJson.SimpleArrayJson; int strLength = str.Length; var buffer = new byte[4096]; for (var i = 0; i < strLength; i++) { buffer[i] = (byte)str[i]; } var json = new JsonParser(buffer, strLength); var parseObject = json.Parse(); var phoneNum = (string)parseObject[0]; var age = (int)parseObject[1]; Assert.Equal(phoneNum, "425-214-3151"); Assert.Equal(age, 25); str = TestJson.SimpleObjectJson; strLength = str.Length; buffer = new byte[4096]; for (var i = 0; i < strLength; i++) { buffer[i] = (byte)str[i]; } json = new JsonParser(buffer, strLength); parseObject = json.Parse(); age = (int)parseObject["age"]; var ageStr = (string)parseObject["age"]; var first = (string)parseObject["first"]; var last = (string)parseObject["last"]; var phoneNumber = (string)parseObject["phoneNumber"]; var street = (string)parseObject["street"]; var city = (string)parseObject["city"]; var zip = (int)parseObject["zip"]; Assert.Equal(age, 30); Assert.Equal(ageStr, "30"); Assert.Equal(first, "John"); Assert.Equal(last, "Smith"); Assert.Equal(phoneNumber, "425-214-3151"); Assert.Equal(street, "1 Microsoft Way"); Assert.Equal(city, "Redmond"); Assert.Equal(zip, 98052); }
public void JsonParserFailsToParseDoubleDoubleQuotes() { string createTableJsonResponse = GetReportTextContent(); JsonItem job; using (var jsonParser = new JsonParser(createTableJsonResponse)) { job = jsonParser.ParseNext(); if (job.IsError) { JsonParseError error = (JsonParseError)job; Assert.Fail(error.ToString()); } } string queryText; Assert.IsTrue(job.GetProperty("execute").TryGetValue(out queryText), "unable to retrieve the query text string"); Assert.AreEqual("\"select * from hivesampletable limit10\"", queryText); }
static void Main(string[] args) { var jsonText = @"[{""id"":""123"", ""name"":""Mr. Big"", ""age"":30}, {""id"":""123"", ""name"":""Mr. X""}]"; var jsonParser = new JsonParser (jsonText, true); Console.WriteLine ("ParseResult: {0}", jsonParser); dynamic[] users = jsonParser.DynamicResult.GetChildren (); foreach (dynamic user in users) { string id = user.id ; string name = user.name ; double age = user.age.ConvertToFloat (-1.0); Console.WriteLine ("Record: id:{0}, name:{1}, age:{2}", id, name, age); } }
/// <summary> /// Parses the specified JSON input. /// </summary> public Node Parse(String input) { Assume.NotNull(input, nameof(input)); var stream = new AntlrInputStream(input); ITokenSource lexer = new JsonLexer(stream); ITokenStream tokens = new CommonTokenStream(lexer); var parser = new JsonParser(tokens) { BuildParseTree = true }; var tree = parser.start(); var treeFactory = new StandardJsonSyntaxTreeFactory(); var syntaxBuilder = new StandardJsonSyntaxTreeBuilder(treeFactory); return syntaxBuilder.Visit(input, tree); }
public void JsonParserFailsToParseEmptyObject() { string createTableJsonResponse = "{\"status\": \" abc\\t abc\\r abc\\n abc\\b abc\\f abc\\\\ abc\\f abc\\u0041 \", \"number\" : 2 }"; JsonItem job; using (var jsonParser = new JsonParser(createTableJsonResponse)) { job = jsonParser.ParseNext(); if (job.IsError) { JsonParseError error = (JsonParseError)job; Assert.Fail(error.ToString()); } } string statusString; Assert.IsTrue(job.GetProperty("status").TryGetValue(out statusString), "unable to retrieve the status string"); Assert.AreEqual(" abc\t abc\r abc\n abc\b abc\f abc\\ abc\f abcA ", statusString); }
public void BasicParserTest() { var parser = new JsonParser(); var result = parser.Parse("[0,1,null,true,false]"); result.IsInstanceOf<ArrayValue>(); var array = result as ArrayValue; array.Values.Count.Is(5); array.Values[0].IsInstanceOf<NumericValue>(); var num = array.Values[0] as NumericValue; num.Value.Is(0); array.Values[1].IsInstanceOf<NumericValue>(); num = array.Values[1] as NumericValue; num.Value.Is(1); array.Values[2].IsInstanceOf<NullValue>(); array.Values[3].IsInstanceOf<BoolValue>(); var boolVal = array.Values[3] as BoolValue; boolVal.Value.IsTrue(); boolVal = array.Values[4] as BoolValue; boolVal.Value.IsFalse(); result = parser.Parse("{\"aa\":\"xx\"}"); result.IsInstanceOf<ObjectValue>(); var objValue = result as ObjectValue; objValue.Fields.Count.Is(1); objValue.Fields[0].Name.Is("aa"); objValue.Fields[0].Value.IsInstanceOf<StringValue>(); var strVal = objValue.Fields[0].Value as StringValue; strVal.Value.Is("xx"); var fields = result.MapValue((ObjectValue o) => o.Fields); fields.IsNotNull(); var type = TypeRepository.CreateTypeWithName("test", objValue); type.Name.Is("test"); var field = type.Fields["aa"]; field.IsNotNull(); field.TypeName.Is("string"); }
public async void GetItemsTokenPagination() { string endPoint = "http://MyRestApiEndPoint.com"; var maxRecordsParam = 20; var paginationParameterName = "token"; var pageSizeParemeterName = "limit"; var responseTokenName = "meta.next_token"; var orderByParameterName = "order_by"; var orderByParameterValue = "date"; var orderDirectionParameterName = "order"; var orderDirectionParameterValue = "DESC"; var paginationConfig = new TokenPagination(paginationParameterName, responseTokenName, pageSizeParemeterName) { OrderByParameterName = orderByParameterName, OrderByParameterValue = orderByParameterValue, OrderDirectionParameterName = orderDirectionParameterName, OrderDirectionParameterValue= orderDirectionParameterValue }; var config = new RestApiDataConfig() { Url = new Uri(endPoint), PaginationConfig = paginationConfig }; var parser = new JsonParser<MySchema>(); _dataProvider = new RestApiDataProvider(); var items = await _dataProvider.LoadDataAsync(config, maxRecordsParam, parser); foreach (var item in items) { Items.Add(item); } }
public bool TryParse <T>(string source, ref int index, [NotNullWhen(true)] out JsonPathExpression?expression, [NotNullWhen(false)] out string?errorMessage) { PathExpression <T> node; var isLocal = source[index] == '@'; if (!JsonPathParser.TryParse(source, ref index, out var path, out errorMessage) && // Swallow this error from the path parser and assume the path just ended. // If it's really a syntax error, the expression parser should catch it. errorMessage != "Unrecognized JSON Path element.") { expression = null !; return(false); } var lastOp = path !.Operators.Last(); if (lastOp is NameOperator name) { path.Operators.Remove(name); if (name.Name == "indexOf") { if (source[index] != '(') { errorMessage = "Expected '('. 'indexOf' operator requires a parameter."; expression = null !; return(false); } index++; if (!JsonParser.TryParse(source, ref index, out var parameter, out errorMessage, true) && // Swallow this error from the JSON parser and assume the value just ended. // If it's really a syntax error, the expression parser should catch it. errorMessage != "Expected \',\', \']\', or \'}\'.") { errorMessage = $"Error parsing parameter for 'indexOf' expression: {errorMessage}."; expression = null !; return(false); } if (source[index] != ')') { errorMessage = "Expected ')'."; expression = null !; return(false); } index++; node = new IndexOfExpression <T>(path, isLocal, parameter !); } else { node = new NameExpression <T>(path, isLocal, name.Name); } } else if (lastOp is LengthOperator length) { path.Operators.Remove(length); node = new LengthExpression <T>(path, isLocal); } else if (lastOp is ArrayOperator array) { path.Operators.Remove(array); var query = array.Query as SliceQuery; var constant = query?.Slices.FirstOrDefault()?.Index; if (query == null || query.Slices.Count() != 1 || !constant.HasValue) { errorMessage = "JSON Path expression indexers only support single constant values."; expression = null !; return(false); } node = new ArrayIndexExpression <T>(path, isLocal, constant.Value); } else { throw new NotImplementedException(); } expression = new PathValueExpression <T>(node); return(true); }
public WalletEndpointClient(string endpoint) { this.endpoint = endpoint; this.jsonParser = new JsonParser(); }
public JsValue Parse(JsValue thisObject, JsValue[] arguments) { var parser = new JsonParser(_engine); return parser.Parse(TypeConverter.ToString(arguments[0])); }
/// <summary> /// The GetJsonBag. /// </summary> /// <param name="tmsg">The tmsg<see cref="DealMessage"/>.</param> /// <param name="JsonString">The JsonString<see cref="string"/>.</param> /// <param name="_bag">The _bag<see cref="IDictionary{string, object}"/>.</param> public static void GetJsonBag(this DealMessage tmsg, string JsonString, IDictionary <string, object> _bag) { _bag.Add(JsonParser.FromJson(JsonString)); }
private QueueItem CreateRefreshQueueItem(Action <GuestControllerResult <RefreshResponse> > callback) { Action <GuestControllerResult <RefreshResponse> > failureCallback = delegate(GuestControllerResult <RefreshResponse> r) { callback(new GuestControllerResult <RefreshResponse>(success: false, r.Response, r.ResponseHeaders)); }; QueueItem queueItem = CreateQueueItem("/client/{client-id}/guest/refresh-auth/{refresh-token}", HttpMethod.POST, new EmptyRequest(), GuestControllerAuthenticationType.None, delegate(GuestControllerResult <RefreshResponse> r) { if (!r.Success) { AuthenticationUnavailableEventArgs e = new AuthenticationUnavailableEventArgs(); this.OnAuthenticationLost(this, e); failureCallback(r); } else { GuestApiErrorCollection guestApiErrorCollection = r.Response.error; RefreshData data = r.Response.data; IRefreshGuestControllerTokenError refreshGuestControllerTokenError = GuestControllerErrorParser.GetGuestControllerTokenRefreshError(guestApiErrorCollection); if (refreshGuestControllerTokenError is IRefreshRequiresLegalMarketingUpdateError) { refreshGuestControllerTokenError = null; guestApiErrorCollection = null; this.OnLegalMarketingUpdateRequired(this, new LegalMarketingUpdateRequiredEventArgs()); } if (refreshGuestControllerTokenError is IRefreshTokenGatedLocationError) { logger.Critical("Location gated during Guest Controller token refresh"); AuthenticationLostGatedCountryEventArgs e2 = new AuthenticationLostGatedCountryEventArgs(); this.OnAuthenticationLost(this, e2); failureCallback(r); } else if (refreshGuestControllerTokenError is IRefreshProfileDisabledError || refreshGuestControllerTokenError is IRefreshTemporaryBanError) { logger.Critical("Banned during Guest Controller token refresh"); AccountBannedEventArgs e3 = new AccountBannedEventArgs(logger, null); this.OnAuthenticationLost(this, e3); failureCallback(r); } else if (refreshGuestControllerTokenError != null) { logger.Critical("Guest Controller token refresh error: " + refreshGuestControllerTokenError); AuthenticationRevokedEventArgs e4 = new AuthenticationRevokedEventArgs(); this.OnAuthenticationLost(this, e4); failureCallback(r); } else if (guestApiErrorCollection != null) { logger.Critical("Unhandled error during Guest Controller token refresh: " + JsonParser.ToJson(guestApiErrorCollection)); AuthenticationUnavailableEventArgs e = new AuthenticationUnavailableEventArgs(); this.OnAuthenticationLost(this, e); failureCallback(r); } else if (data == null || data.token == null || data.token.access_token == null || data.token.refresh_token == null) { logger.Critical("Refreshing Guest Controller token returned invalid refresh data: " + JsonParser.ToJson(data)); AuthenticationUnavailableEventArgs e = new AuthenticationUnavailableEventArgs(); this.OnAuthenticationLost(this, e); failureCallback(r); } else { Token token = data.token; database.UpdateGuestControllerToken(token, data.etag); this.OnAccessTokenChanged(this, new GuestControllerAccessTokenChangedEventArgs(token.access_token)); callback(r); } } }); queueItem.RefreshedAccessToken = true; return(queueItem); }
private async void nextStepButton_Click(object sender, RoutedEventArgs e) { //做判断 Dictionary <string, string> regPair = new Dictionary <string, string>(); regPair.Add("ID", idTextBox.Text.Trim()); //TODO:Encryption //string encrypted=Encryption.Encrypt(pswPasswordBox.Password); string encrypted = pswPasswordBox.Password; regPair.Add("PASSWORD", encrypted); regPair.Add("NAME", nameTextBox.Text.Trim()); regPair.Add("STATUS", "OFFLINE"); if (maleRadioButton.IsChecked == true) { regPair.Add("GENDER", "Male"); } else { regPair.Add("GENDER", "Female"); } regPair.Add("CELLPHONE", phonenumTextBox.Text.Trim()); if (studentRadioButton.IsChecked == true) { regPair.Add("Type", "Stu"); regPair.Add("DORMITORY", dormnumTextBox.Text.Trim()); regPair.Add("CLASSNUMBER", classnumTextBox.Text.Trim()); regPair.Add("DIRECTORNAME", directorNameTextBox.Text.Trim()); regPair.Add("DIRECTORCELLPHONE", directorPhonenumTextBox.Text.Trim()); } else { regPair.Add("Type", "Sup"); regPair.Add("BUILDING", buildingTextBox.Text.Trim()); } Packet[] packets = DataParser.Str2Packets(Convert.ToInt32(CommandCode.Register), JsonParser.SerializeObject(regPair)); StaticObj.SendPackets(packets); Packet[] incomming = await StaticObj.ReceivePackets(); int regResult = DataParser.GetPacketCommandCode(incomming[0]); if (regResult == Convert.ToInt32(CommandCode.Succeed)) { await(new MessageDialog("注册成功")).ShowAsync(); //将登录名及加密后的密码写入文件中,以便以后可一键登录 Dictionary <string, string> remember = new Dictionary <string, string>(); remember.Add("ID", idTextBox.Text.Trim()); remember.Add("PASSWORD", encrypted); if (studentRadioButton.IsChecked == true) { remember.Add("ISSTUDENT", "1"); } else { remember.Add("ISSTUDENT", "0"); } var fold = Windows.Storage.ApplicationData.Current.LocalFolder; //打开文件夹 StorageFile file = await fold.CreateFileAsync("Info.json", CreationCollisionOption.ReplaceExisting); //创建文件 await FileIO.WriteTextAsync(file, JsonParser.SerializeObject(remember)); //写入 Frame.BackStack.Clear(); Frame.Navigate(typeof(Login)); } else if (regResult == Convert.ToInt32(CommandCode.RegisterFailed)) { await(new MessageDialog("注册失败")).ShowAsync(); } else { await(new MessageDialog("该用户名已被注册")).ShowAsync(); } }
public JsValue Parse(JsValue thisObject, JsValue[] arguments) { var parser = new JsonParser(_engine); return parser.Parse(arguments[0].AsString()); }
public static string ParserLangPredictionResposne(string response) { string language = ""; if (string.IsNullOrWhiteSpace(response)) { language = NoPrediction; return(language); } var segmentsArray = JsonParser.ParseArray(response); if (segmentsArray == null) { language = InvalidPrediction; return(language); } if (segmentsArray.Count == 0) { language = InvalidPrediction; return(language); } else if (segmentsArray.Count > 1) { language = MultiLingual; return(language); } var segmentFieldsDict = JsonParser.ParseDictionary(segmentsArray[0]); if (segmentFieldsDict == null) { language = InvalidPrediction; return(language); } if (!segmentFieldsDict.ContainsKey(PredictionsKey)) { language = InvalidPrediction; return(language); } var languageDict = JsonParser.ParseDictionary(segmentFieldsDict[PredictionsKey]); if (languageDict == null) { language = InvalidPrediction; return(language); } if (languageDict.Count == 0) { language = LanguageIndependent; return(language); } double max = 0D; double secondMax = -1D; double min = 2D; foreach (var entry in languageDict) { double confidence = 0D; try { confidence = double.Parse(entry.Value); } catch (Exception) { language = InvalidPrediction; return(language); } if (confidence > max) { secondMax = max; max = confidence; language = entry.Key; } else if (confidence > secondMax) { secondMax = confidence; } if (confidence < min) { min = confidence; } } if (min >= 1D && languageDict.Count > 1) { language = LanguageIndependent; return(language); } else if (max <= ProminentThreshold || max < secondMax * ProminentRatio) { language = NoProminent; return(language); } else { return(language); } }
public void Fill() { using (var unitOfWork = new UnitOfWork(new NbaContext())) { var TeamParser = new TeamsToIEnumerable(); var PlayersParser = new PlayersToIEnumerable(); var PlayerStatisticParser = new JsonParser(); var Teams = TeamParser.Cast(); var Players = PlayersParser.Cast(); var PS = PlayerStatisticParser.Cast(); for (int i = 0; i < Players.Count; i++) { Players.ElementAt(i).PlayerStatistic = PS.ElementAt(i); PS.ElementAt(i).Player = Players.ElementAt(i); } ICollection <League> Leagues = new List <League>(); Leagues.Add(new League() { LeagueEnum = LeaguesEnum.NBA }); Leagues.Add(new League() { LeagueEnum = LeaguesEnum.WNBA }); ICollection <Conference> Conferences = new List <Conference>(); Conferences.Add(new Conference() { ConferenceEnum = ConferencesEnum.Eastern }); Conferences.Add(new Conference() { ConferenceEnum = ConferencesEnum.Western }); ICollection <Devision> Devisions = new List <Devision>(); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.ATLANTIC }); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.CENTRAL }); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.TEAMSNORTHWEST }); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.TEAMSPACIFIC }); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.TEAMSSOUTHEAST }); Devisions.Add(new Devision() { DevisionEnum = DevisionsEnum.TEAMSSOUTHWEST }); unitOfWork.League.AddRange(Leagues); unitOfWork.Conference.AddRange(Conferences); unitOfWork.Devisions.AddRange(Devisions); unitOfWork.Players.AddRange(Players); unitOfWork.Teams.AddRange(Teams); unitOfWork.PlayerStatistic.AddRange(PS); unitOfWork.Complete(); } }
public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName) { _errorCount = 0; var sb = new StringBuilder(); foreach (string s in lines) { sb.Append(s); } string allText = sb.ToString().Trim(); if (!(allText.StartsWith("{", StringComparison.Ordinal) || allText.Contains("dDurationMs", StringComparison.Ordinal))) { return; } var parser = new JsonParser(); Dictionary <string, object> dictionary; try { dictionary = (Dictionary <string, object>)parser.Parse(allText); } catch (ParserException) { return; } foreach (var k in dictionary.Keys) { if (k != "events" || !(dictionary[k] is List <object> captionGroups)) { continue; } foreach (var item in captionGroups) { if (!(item is Dictionary <string, object> line)) { continue; } var text = new StringBuilder(); var start = -1d; var dur = -1d; foreach (var lineKey in line.Keys) { if (lineKey == "segs") { if (line[lineKey] is List <object> l) { foreach (var o in l) { if (o is Dictionary <string, object> textDic) { foreach (var tk in textDic.Keys) { if (tk == "utf8") { text.Append(" " + string.Join(Environment.NewLine, textDic[tk].ToString().SplitToLines())); } } } } } } else if (lineKey == "tStartMs") { if (double.TryParse(line[lineKey].ToString().Replace(",", "."), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var s)) { start = s; } } else if (lineKey == "dDurationMs") { if (double.TryParse(line[lineKey].ToString().Replace(",", "."), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var s)) { dur = s; } } } var subText = text.ToString() .Replace(" ", " ") .Replace(Environment.NewLine + " ", Environment.NewLine) .Trim(); if (!string.IsNullOrEmpty(subText) && dur > 0) { subtitle.Paragraphs.Add(new Paragraph(subText, start, start + dur)); } } } new FixOverlappingDisplayTimes().Fix(subtitle, new EmptyFixCallback()); subtitle.Renumber(); }
private string getDownloadUrl(string songId) { var urlInfO = JsonParser.Deserialize(HttpHelper.GET(string.Format("http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={0}", songId), DEFAULT_CONFIG)); return(urlInfO.url); }
IEnumerator Login(string userID, string pletformID = "", LoginType loginType = LoginType.GuestLogin) { Debug.Log("로그인 시작"); loginPanel.SetActive(false); //로그인 시 유저 데이터 구성부분 WWWForm form = new WWWForm(); form.AddField("userID", userID, System.Text.Encoding.UTF8); //테스트 아이디로 로그인한다. string googleID = ""; if (PlayerPrefs.HasKey("google")) { googleID = PlayerPrefs.GetString("google"); } else { if (loginType == LoginType.GoogleLogin) { googleID = pletformID; } } string facebookID = ""; if (PlayerPrefs.HasKey("facebook")) { facebookID = PlayerPrefs.GetString("facebook"); } else { if (loginType == LoginType.FacebookLogin) { facebookID = pletformID; } } tipMessageText.text = "로그인 정보를 내려받는 중.."; form.AddField("google", googleID, System.Text.Encoding.UTF8); form.AddField("facebook", facebookID, System.Text.Encoding.UTF8); form.AddField("deviceModel", SystemInfo.deviceModel); form.AddField("deviceID", SystemInfo.deviceUniqueIdentifier); form.AddField("type", (int)loginType); string result = ""; string php = "Login.php"; yield return(StartCoroutine(WebServerConnectManager.Instance.WWWCoroutine(php, form, x => result = x))); JsonData jsonData = ParseCheckDodge(result); PlayerPrefs.SetString("userID", JsonParser.ToString(jsonData["id"].ToString())); if (loginType == LoginType.GoogleLogin) { PlayerPrefs.SetString("google", JsonParser.ToString(jsonData["google"].ToString())); } if (loginType == LoginType.FacebookLogin) { PlayerPrefs.SetString("facebook", JsonParser.ToString(jsonData["facebook"].ToString())); } // 아틀라스 캐싱 string atlasName = "Atlas_Product"; AssetBundleLoadAssetOperation r = AssetBundleManager.LoadAssetAsync("sprite/product", atlasName, typeof(UnityEngine.U2D.SpriteAtlas)); yield return(StartCoroutine(r)); UnityEngine.U2D.SpriteAtlas atlas = r.GetAsset <UnityEngine.U2D.SpriteAtlas>(); if (atlas != null) { if (!AssetLoader.cachedAtlasDic.ContainsKey(atlasName)) { AssetLoader.cachedAtlasDic.Add(atlasName, atlas); } } string atlasName2 = "Atlas_Material"; AssetBundleLoadAssetOperation r2 = AssetBundleManager.LoadAssetAsync("sprite/material", atlasName2, typeof(UnityEngine.U2D.SpriteAtlas)); yield return(StartCoroutine(r2)); UnityEngine.U2D.SpriteAtlas atlas2 = r2.GetAsset <UnityEngine.U2D.SpriteAtlas>(); if (atlas2 != null) { if (!AssetLoader.cachedAtlasDic.ContainsKey(atlasName2)) { AssetLoader.cachedAtlasDic.Add(atlasName2, atlas2); } } //// 게임 데이타 초기화 끝날 때 까지 대기 //while (!GameDataManager.isInitialized) // yield return null; if (User.Instance) { User.Instance.InitUserData(jsonData); } Debug.Log("유저 데이터 초기화"); while (!User.isInitialized) { yield return(null); } Debug.Log("완료"); // 유저 데이터 초기화 시작 StartCoroutine(UserDataManager.Instance.Init()); // 유저 데이터 초기화 완료 했는가 체크 while (!UserDataManager.isInitialized) { yield return(null); } tipMessageText.text = "왕국으로 진입중.."; Debug.Log("Login UserID : " + JsonParser.ToString(jsonData["id"])); //enterButton.SetActive(true); //if (onFadeOutStart != null) // onFadeOutStart(); ////페이드아웃 기다리는 시간 //yield return new WaitForSeconds(1.5f); yield return(StartCoroutine(LoadingManager.FadeOutScreen())); string nextSceneBundleName = "scene/lobby"; string nextSceneName = "Lobby"; AssetBundleLoadOperation operation = AssetBundleManager.LoadLevelAsync(nextSceneBundleName, nextSceneName, true); //// 몬스터 풀 초기화 끝났는가 체크 //while (!MonsterPool.Instance) // yield return null; //while (!MonsterPool.Instance.isInitialization) // yield return null; //while (!Battle.Instance || !Battle.Instance.isInitialized) // yield return null; while (!operation.IsDone()) { yield return(null); } versionText.gameObject.SetActive(false); messagePanel.SetActive(false); StopCoroutine(messageCoroutine()); //while (!UILoginManager.isFinished) // yield return null; Scene lobby = SceneManager.GetSceneByName("Lobby"); Scene login = SceneManager.GetSceneByName("Login"); Scene preLogin = SceneManager.GetSceneByName("PreLogin"); SceneManager.SetActiveScene(lobby); SceneManager.UnloadSceneAsync(login); SceneManager.UnloadSceneAsync(preLogin); }
public JsonParserTest() { _jsonParser = new JsonParser(); }
public List <string> Translate(string sourceLanguage, string targetLanguage, List <Paragraph> sourceParagraphs) { //TODO: Get access token... var input = new StringBuilder(); var formatList = new List <Formatting>(); for (var index = 0; index < sourceParagraphs.Count; index++) { var p = sourceParagraphs[index]; var f = new Formatting(); formatList.Add(f); if (input.Length > 0) { input.Append(","); } var text = f.SetTagsAndReturnTrimmed(TranslationHelper.PreTranslate(p.Text, sourceLanguage), sourceLanguage); text = f.UnBreak(text, p.Text); input.Append("\"" + Json.EncodeJsonText(text) + "\""); } var request = (HttpWebRequest)WebRequest.Create($"https://translation.googleapis.com/v3/{_projectNumberOrId}:translateText"); request.Proxy = Utilities.GetProxy(); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { var requestJson = "{ \"sourceLanguageCode\": \"" + sourceLanguage + "\", \"targetLanguageCode\": \"" + targetLanguage + "\", " + "\"contents\": [" + input + "]}"; streamWriter.Write(requestJson); } var response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); var skipCount = 0; var resultList = new List <string>(); var parser = new JsonParser(); var x = (Dictionary <string, object>)parser.Parse(content); foreach (var k in x.Keys) { if (x[k] is Dictionary <string, object> v) { foreach (var innerKey in v.Keys) { if (v[innerKey] is List <object> l) { foreach (var o2 in l) { if (o2 is Dictionary <string, object> v2) { foreach (var innerKey2 in v2.Keys) { if (v2[innerKey2] is string translatedText) { translatedText = Regex.Unescape(translatedText); translatedText = string.Join(Environment.NewLine, translatedText.SplitToLines()); translatedText = TranslationHelper.PostTranslate(translatedText, targetLanguage); if (resultList.Count - skipCount < formatList.Count) { translatedText = formatList[resultList.Count - skipCount].ReAddFormatting(translatedText); translatedText = formatList[resultList.Count - skipCount].ReBreak(translatedText, targetLanguage); } resultList.Add(translatedText); } } } } } } } } return(resultList); }
/// <summary> /// The SetJsonString. /// </summary> /// <param name="tmsg">The tmsg<see cref="DealMessage"/>.</param> /// <param name="jsonbag">The jsonbag<see cref="IDictionary{string, object}"/>.</param> /// <returns>The <see cref="string"/>.</returns> public static string SetJsonString(this DealMessage tmsg, IDictionary <string, object> jsonbag) { return(JsonParser.ToJson(jsonbag)); }
public JsonSeatTypeRepository(JsonParser <SeatType> jsonParser, StorageOptions options) : base(jsonParser, options) { }
/// <summary> /// 在此页将要在 Frame 中显示时进行调用。 /// </summary> /// <param name="e">描述如何访问此页的事件数据。 /// 此参数通常用于配置页。</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { Windows.Phone.UI.Input.HardwareButtons.BackPressed += (sender, arg) => { arg.Handled = true; }; locationBox.Clear(); Geolocator geolocator = new Geolocator(); Geoposition geoposition = null; BasicGeoposition supervisorPosition = new BasicGeoposition(); try { geoposition = await geolocator.GetGeopositionAsync(); supervisorPosition.Longitude = geoposition.Coordinate.Point.Position.Longitude; supervisorPosition.Latitude = geoposition.Coordinate.Point.Position.Latitude; supervisorPosition.Altitude = geoposition.Coordinate.Point.Position.Altitude; MapIcon supervisorIcon = new MapIcon(); supervisorIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/PinkPushPin.png")); supervisorIcon.NormalizedAnchorPoint = new Point(0.25, 0.9); supervisorIcon.Location = new Geopoint(supervisorPosition); MapControl.Center = geoposition.Coordinate.Point; } catch { } StaticObj.SendPackets(DataParser.Str2Packets(Convert.ToInt32(CommandCode.GetLocation), "")); Packet[] incomming = await StaticObj.ReceivePackets(); if (DataParser.GetPacketCommandCode(incomming[0]) == Convert.ToInt32(CommandCode.ReturnLocation)) { List <Dictionary <string, string> > locationDict = JsonParser.DeserializeListOfDictionaryObject(DataParser.Packets2Str(incomming)); foreach (Dictionary <string, string> dic in locationDict) { BasicGeoposition position = new BasicGeoposition(); position.Longitude = Convert.ToDouble(dic["LONGITUDE"]); position.Latitude = Convert.ToDouble(dic["LATITUDE"]); position.Altitude = Convert.ToDouble(dic["ALTITUDE"]); MapIcon studentIcon = new MapIcon(); studentIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/PinkPushPin.png")); studentIcon.NormalizedAnchorPoint = new Point(0.25, 0.9); studentIcon.Location = new Geopoint(position); MapControl.MapElements.Add(studentIcon); LocationContent locationContent = new LocationContent(); locationContent.ID = dic["ID"]; locationContent.Time = dic["TIME"]; locationContent.PositionSource = dic["POSITIONSOURCE"]; double distance = GetDistance(geoposition.Coordinate.Point.Position.Latitude, geoposition.Coordinate.Point.Position.Longitude, Convert.ToDouble(dic["LATITUDE"]), Convert.ToDouble(dic["LONGITUDE"])); if (distance < 1000) { locationContent.Distance = "距离:" + distance.ToString("0.0") + "米"; } else { locationContent.Distance = "距离:" + (distance / 1000).ToString("0.00") + "千米"; } double azimuth = GetAzimuth(geoposition.Coordinate.Point.Position.Latitude, geoposition.Coordinate.Point.Position.Longitude, Convert.ToDouble(dic["LATITUDE"]), Convert.ToDouble(dic["LONGITUDE"])); if (azimuth == 0) { locationContent.Azimuth = "北"; } else if (azimuth > 0 && azimuth < 90) { locationContent.Azimuth = "北偏东\t" + azimuth.ToString("0.000") + "°"; } else if (azimuth == 90) { locationContent.Azimuth = "东"; } else if (azimuth > 90 && azimuth < 180) { locationContent.Azimuth = "南偏东\t" + (180 - azimuth).ToString("0.000") + "°"; } else if (azimuth == 180) { locationContent.Azimuth = "南"; } else if (azimuth > 180 && azimuth < 270) { locationContent.Azimuth = "南偏西\t" + (azimuth - 270).ToString("0.000") + "°"; } else if (azimuth == 270) { locationContent.Azimuth = "西"; } else if (azimuth > 270 && azimuth < 360) { locationContent.Azimuth = "北偏西\t" + (360 - azimuth).ToString("0.000") + "°"; } locationBox.Add(locationContent); } InspectionList.ItemsSource = locationBox; } ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed; }
public void baidu() { try { // string[] citys = textBox1.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None); if (textBox3.Text == "") { MessageBox.Show("请输入关键字"); return; } ArrayList citys = new ArrayList(); foreach (var item in comboBox2.Items) { citys.Add(item); } if (comboBox1.Text == "全国") { citys.Add("北京"); //获取 citycode; citys.Add("上海"); citys.Add("天津"); citys.Add("重庆"); citys.Add("广州"); citys.Add("深圳"); citys.Add("杭州"); } citys.RemoveAt(0); string[] keywords = textBox3.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None); int pages = 200; foreach (string city in citys) { int cityid = getcityId(city); //获取 citycode; if (comboBox1.Text.Trim() == "北京") { cityid = getcityId("北京市"); //获取 citycode; } else if (comboBox1.Text == "上海") { cityid = getcityId("上海市"); //获取 citycode; } else if (comboBox1.Text == "天津") { cityid = getcityId("天津市"); //获取 citycode; } else if (comboBox1.Text == "重庆") { cityid = getcityId("重庆市"); //获取 citycode; } else if (comboBox2.Text != "全省") { cityid = getcityId(comboBox2.Text); //获取 citycode; } foreach (string keyword in keywords) { for (int i = 0; i <= pages; i++) { int j = i - 1 > 0 ? i - 1 : 0; String Url = "https://map.baidu.com/?newmap=1&reqflag=pcmap&biz=1&from=webmap&da_par=direct&pcevaname=pc4.1&qt=con&from=webmap&c=" + cityid + "&wd=" + keyword + "&wd2=&pn=" + i + "&nn=" + j + "0&db=0&sug=0&addr=0&pl_data_type=cater&pl_price_section=0%2C%2B&pl_sort_type=data_type&pl_sort_rule=0&pl_discount2_section=0%2C%2B&pl_groupon_section=0%2C%2B&pl_cater_book_pc_section=0%2C%2B&pl_hotel_book_pc_section=0%2C%2B&pl_ticket_book_flag_section=0%2C%2B&pl_movie_book_section=0%2C%2B&pl_business_type=cater&pl_business_id=&da_src=pcmappg.poi.page&on_gel=1&src=7&gr=3&l=12"; string html = method.GetUrl(Url, "utf-8"); MatchCollection TitleMatchs = Regex.Matches(html, @"""primary_uid"":""([\s\S]*?)""", RegexOptions.IgnoreCase); ArrayList lists = new ArrayList(); foreach (Match NextMatch in TitleMatchs) { lists.Add(NextMatch.Groups[1].Value); } if (lists.Count == 0) //当前页没有网址数据跳过之后的网址采集,进行下个foreach采集 { break; } string tm1 = DateTime.Now.ToString(); //获取系统时间 JsonParser jsonParser = JsonConvert.DeserializeObject <JsonParser>(html); foreach (Content content in jsonParser.Content) { if (content.tel != null && !finishes.Contains(content.name)) { finishes.Add(content.name); ListViewItem lv1 = listView2.Items.Add(listView2.Items.Count.ToString()); lv1.SubItems.Add(content.name); lv1.SubItems.Add(content.tel); lv1.SubItems.Add(content.addr); lv1.SubItems.Add(keyword.Trim()); if (listView2.Items.Count - 1 > 1) { listView2.EnsureVisible(listView2.Items.Count - 1); } if (status == false) { return; } } Application.DoEvents(); Thread.Sleep(10); //内容获取间隔,可变量 } } } } button2.Enabled = true; } catch (System.Exception ex) { ex.ToString(); } }
public void JsonParser_Parse_InputGoodJsonSuccsess() { var jsonParse = new JsonParser(); var res = jsonParse.Parse(testJsonGood); }
public bool LoadFromJson(string jsonStr) { TriadCardDB cardDB = TriadCardDB.Get(); TriadNpcDB npcDB = TriadNpcDB.Get(); ownedCards.Clear(); completedNpcs.Clear(); lastDeck.Clear(); favDecks.Clear(); try { JsonParser.ObjectValue jsonOb = JsonParser.ParseJson(jsonStr); JsonParser.ObjectValue uiOb = (JsonParser.ObjectValue)jsonOb["ui", null]; if (uiOb != null) { JsonParser.Value BoolTrue = new JsonParser.BoolValue(true); JsonParser.Value BoolFalse = new JsonParser.BoolValue(false); useXInput = (JsonParser.BoolValue)uiOb["xInput", BoolTrue]; alwaysOnTop = (JsonParser.BoolValue)uiOb["onTop", BoolFalse]; forcedLanguage = (JsonParser.StringValue)uiOb["lang", null]; TryGettingFloatValue(uiOb, "fontSize", ref fontSize); TryGettingFloatValue(uiOb, "markerCard", ref markerDurationCard); TryGettingFloatValue(uiOb, "markerSwap", ref markerDurationSwap); TryGettingFloatValue(uiOb, "markerCactpot", ref markerDurationCactpot); TryGettingIntValue(uiOb, "lastNpcId", ref lastNpcId); TryGettingFloatValue(uiOb, "lastWidth", ref lastWidth); TryGettingFloatValue(uiOb, "lastHeight", ref lastHeight); fontSize = Math.Min(Math.Max(fontSize, 10), 40); } JsonParser.ObjectValue cloudOb = (JsonParser.ObjectValue)jsonOb["cloud", null]; if (cloudOb != null) { useCloudStorage = (JsonParser.BoolValue)cloudOb["use", JsonParser.BoolValue.Empty]; cloudToken = (JsonParser.StringValue)cloudOb["token", null]; } JsonParser.ArrayValue cardsArr = (JsonParser.ArrayValue)jsonOb["cards", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value value in cardsArr.entries) { int cardId = (JsonParser.IntValue)value; ownedCards.Add(cardDB.cards[cardId]); } JsonParser.ArrayValue npcsArr = (JsonParser.ArrayValue)jsonOb["npcs", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value value in npcsArr.entries) { int npcId = (JsonParser.IntValue)value; completedNpcs.Add(npcDB.npcs[npcId]); } JsonParser.ArrayValue decksArr = (JsonParser.ArrayValue)jsonOb["decks", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value value in decksArr.entries) { JsonParser.ObjectValue deckOb = (JsonParser.ObjectValue)value; int npcId = (JsonParser.IntValue)deckOb["id"]; TriadNpc npc = TriadNpcDB.Get().npcs[npcId]; if (npc != null) { TriadDeck deckCards = new TriadDeck(); cardsArr = (JsonParser.ArrayValue)deckOb["cards", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value cardValue in cardsArr.entries) { int cardId = (JsonParser.IntValue)cardValue; deckCards.knownCards.Add(cardDB.cards[cardId]); } lastDeck.Add(npc, deckCards); } } JsonParser.ArrayValue favDecksArr = (JsonParser.ArrayValue)jsonOb["favDecks", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value value in favDecksArr.entries) { JsonParser.ObjectValue deckOb = (JsonParser.ObjectValue)value; TriadDeckNamed deckCards = new TriadDeckNamed(); cardsArr = (JsonParser.ArrayValue)deckOb["cards", JsonParser.ArrayValue.Empty]; foreach (JsonParser.Value cardValue in cardsArr.entries) { int cardId = (JsonParser.IntValue)cardValue; deckCards.knownCards.Add(cardDB.cards[cardId]); } if (deckCards.knownCards.Count > 0) { deckCards.Name = deckOb["name", JsonParser.StringValue.Empty]; favDecks.Add(deckCards); } } JsonParser.ObjectValue imageHashesOb = (JsonParser.ObjectValue)jsonOb["images", null]; if (imageHashesOb != null) { customHashes = ImageHashDB.Get().LoadImageHashes(imageHashesOb); ImageHashDB.Get().hashes.AddRange(customHashes); } } catch (Exception ex) { Logger.WriteLine("Loading failed! Exception:" + ex); } Logger.WriteLine("Loaded player cards: " + ownedCards.Count + ", npcs: " + completedNpcs.Count + ", hashes: " + customHashes.Count); return(ownedCards.Count > 0); }
protected virtual object ParseRequest(TextReader input) { if (input == null) throw new ArgumentNullException("input"); JsonParser parser = (JsonParser) _serviceProvider.GetService(typeof(JsonParser)); if (parser == null) parser = new JsonParser(); return parser.Parse(input); }
public void SaveFile(string path) { // Leave, until ship serialization is fixed return; m_log.Write("Saving " + path); ActiveFile.FilePath = path; File.Delete(path); if (ActiveFile is StarboundDungeon) { JsonParser parser = new JsonParser(path); parser.SerializeJson<StarboundDungeon>((StarboundDungeon)ActiveFile); } else if (ActiveFile is StarboundShip) { JsonParser parser = new JsonParser(path); parser.SerializeJson<StarboundShip>((StarboundShip)ActiveFile); } }
public void AddParser( string key, JsonParser parser ) { m_parsers.Add(key, parser); }
uint? ReadCountUsingNonAllocatingDom(ReadOnlySpan<byte> json) { var parser = new JsonParser(json.CreateArray(), json.Length); // TODO: eliminate allocation JsonParseObject jsonObject = parser.Parse(); uint count = (uint)jsonObject["Count"]; return count; }
private void LoadLevel(string level, string episode) { string levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", episode, level); using (Stream s = FileOp.Open(PathOp.Combine(levelPath, ".res"), FileAccessMode.Read)) { // ToDo: Cache parser, move JSON parsing to ContentResolver JsonParser json = new JsonParser(); LevelHandler.LevelConfigJson config = json.Parse <LevelHandler.LevelConfigJson>(s); //if (config.Version.LayerFormat > LevelHandler.LayerFormatVersion || config.Version.EventSet > LevelHandler.EventSetVersion) { // throw new NotSupportedException("Version not supported"); //} Console.WriteLine("Loading level \"" + config.Description.Name + "\"..."); defaultNextLevel = config.Description.NextLevel; defaultSecretLevel = config.Description.SecretLevel; ambientLightDefault = config.Description.DefaultLight; ambientLightCurrent = ambientLightTarget = ambientLightDefault * 0.01f; string tilesetPath = PathOp.Combine(DualityApp.DataDirectory, "Tilesets", config.Description.DefaultTileset); ColorRgba[] tileMapPalette = TileSet.LoadPalette(PathOp.Combine(tilesetPath, ".palette")); ContentResolver.Current.ApplyBasePalette(tileMapPalette); tileMap = new TileMap(this, config.Description.DefaultTileset, (config.Description.Flags & LevelHandler.LevelFlags.HasPit) != 0); // Read all layers config.Layers.Add("Sprite", new LevelHandler.LevelConfigJson.LayerSection { XSpeed = 1, YSpeed = 1 }); foreach (var layer in config.Layers.OrderBy(layer => layer.Value.Depth)) { LayerType type; if (layer.Key == "Sprite") { type = LayerType.Sprite; } else if (layer.Key == "Sky") { type = LayerType.Sky; if (layer.Value.BackgroundStyle != 0 /*Plain*/ && layer.Value.BackgroundColor != null && layer.Value.BackgroundColor.Count >= 3) { camera.GetComponent <Camera>().ClearColor = new ColorRgba((byte)layer.Value.BackgroundColor[0], (byte)layer.Value.BackgroundColor[1], (byte)layer.Value.BackgroundColor[2]); } } else { type = LayerType.Other; } tileMap.ReadLayerConfiguration(type, levelPath, layer.Key, layer.Value); } // Read animated tiles string animTilesPath = PathOp.Combine(levelPath, "Animated.tiles"); if (FileOp.Exists(animTilesPath)) { tileMap.ReadAnimatedTiles(animTilesPath); } CameraController controller = camera.GetComponent <CameraController>(); controller.ViewRect = new Rect(tileMap.Size * tileMap.Tileset.TileSize); // Read events //eventMap = new EventMap(this, tileMap.Size); //string eventsPath = PathOp.Combine(levelPath, "Events.layer"); //if (FileOp.Exists(animTilesPath)) { // eventMap.ReadEvents(eventsPath, config.Version.LayerFormat, difficulty); //} levelTexts = config.TextEvents ?? new Dictionary <int, string>(); GameObject tilemapHandler = new GameObject("TilemapHandler"); tilemapHandler.Parent = rootObject; tilemapHandler.AddComponent(tileMap); // Load default music //musicPath = PathOp.Combine(DualityApp.DataDirectory, "Music", config.Description.DefaultMusic); //music = DualityApp.Sound.PlaySound(new OpenMptStream(musicPath)); //music.BeginFadeIn(0.5f); } }
private void IncomingListener() { keepalive = true; InstanceProvider.GetServiceLogger().AppendLine("Established connection! Listening for incoming packets!"); int AvailBytes = 0; int byteCount = 0; while (InstanceProvider.GetClientServiceAlive()) { try { byte[] buffer = new byte[4]; AvailBytes = client.Client.Available; while (AvailBytes != 0) // Recieve data from client. { byteCount = stream.Read(buffer, 0, 4); int expectedLen = BitConverter.ToInt32(buffer, 0); buffer = new byte[expectedLen]; byteCount = stream.Read(buffer, 0, expectedLen); NetworkMessageSource msgSource = (NetworkMessageSource)buffer[0]; NetworkMessageDestination msgDest = (NetworkMessageDestination)buffer[1]; NetworkMessageTypes msgType = (NetworkMessageTypes)buffer[2]; NetworkMessageStatus msgStatus = (NetworkMessageStatus)buffer[3]; string data = GetOffsetString(buffer); string[] dataSplit = null; switch (msgDest) { case NetworkMessageDestination.Server: JsonParser message; switch (msgType) { case NetworkMessageTypes.PropUpdate: message = JsonParser.Deserialize(data); List <Property> propList = message.Value.ToObject <List <Property> >(); Property prop = propList.First(p => p.KeyName == "server-name"); InstanceProvider.GetBedrockServer(prop.Value).serverInfo.ServerPropList = propList; InstanceProvider.GetConfigManager().SaveServerProps(InstanceProvider.GetBedrockServer(prop.Value).serverInfo, true); InstanceProvider.GetConfigManager().LoadConfigs(); InstanceProvider.GetBedrockServer(prop.Value).CurrentServerStatus = BedrockServer.ServerStatus.Stopping; while (InstanceProvider.GetBedrockServer(prop.Value).CurrentServerStatus == BedrockServer.ServerStatus.Stopping) { Thread.Sleep(100); } InstanceProvider.GetBedrockServer(prop.Value).StartControl(InstanceProvider.GetBedrockService()._hostControl); SendData(NetworkMessageSource.Server, NetworkMessageDestination.Client, NetworkMessageTypes.PropUpdate); break; case NetworkMessageTypes.Restart: RestartServer(data, false); break; case NetworkMessageTypes.Backup: RestartServer(data, true); break; case NetworkMessageTypes.Command: dataSplit = data.Split(';'); InstanceProvider.GetBedrockServer(dataSplit[0]).StdInStream.WriteLine(dataSplit[1]); InstanceProvider.GetServiceLogger().AppendLine($"Sent command {dataSplit[1]} to stdInput stream"); break; } break; case NetworkMessageDestination.Service: switch (msgType) { case NetworkMessageTypes.Connect: InstanceProvider.GetHostInfo().ServiceLog = InstanceProvider.GetServiceLogger().Log; string jsonString = JsonParser.Serialize(JsonParser.FromValue(InstanceProvider.GetHostInfo())); byte[] stringAsBytes = GetBytes(jsonString); SendData(stringAsBytes, NetworkMessageSource.Service, NetworkMessageDestination.Client, NetworkMessageTypes.Connect); heartbeatRecieved = false; break; case NetworkMessageTypes.Disconnect: DisconnectClient(); break; case NetworkMessageTypes.Heartbeat: if (InstanceProvider.GetHeartbeatThreadAlive()) { heartbeatRecieved = true; } else { InstanceProvider.InitHeartbeatThread(new ThreadStart(SendBackHeatbeatSignal)).Start(); Thread.Sleep(500); heartbeatRecieved = true; } break; case NetworkMessageTypes.ConsoleLogUpdate: StringBuilder srvString = new StringBuilder(); string[] split = data.Split('|'); for (int i = 0; i < split.Length; i++) { dataSplit = split[i].Split(';'); string srvName = dataSplit[0]; int srvTextLen; int clientCurLen; int loop; if (srvName != "Service") { ServerLogger srvText = InstanceProvider.GetBedrockServer(srvName).serverInfo.ConsoleBuffer; srvTextLen = srvText.Count(); clientCurLen = int.Parse(dataSplit[1]); loop = clientCurLen; while (loop < srvTextLen) { srvString.Append($"{srvName};{srvText.FromIndex(loop)};{loop}|"); loop++; } } else { ServiceLogger srvText = InstanceProvider.GetServiceLogger(); srvTextLen = srvText.Count(); clientCurLen = int.Parse(dataSplit[1]); loop = clientCurLen; while (loop < srvTextLen) { srvString.Append($"{srvName};{srvText.FromIndex(loop)};{loop}|"); loop++; } } } if (srvString.Length > 1) { srvString.Remove(srvString.Length - 1, 1); stringAsBytes = GetBytes(srvString.ToString()); SendData(stringAsBytes, NetworkMessageSource.Server, NetworkMessageDestination.Client, NetworkMessageTypes.ConsoleLogUpdate); } break; } break; } AvailBytes = client.Client.Available; } Thread.Sleep(200); } catch (OutOfMemoryException) { InstanceProvider.GetServiceLogger().AppendLine(""); } catch (ObjectDisposedException e) { InstanceProvider.GetServiceLogger().AppendLine("Client was disposed! Killing thread..."); break; } catch (ThreadAbortException) { } catch (JsonException e) { InstanceProvider.GetServiceLogger().AppendLine($"Error parsing json array: {e.Message}"); InstanceProvider.GetServiceLogger().AppendLine($"Stacktrace: {e.InnerException}"); } catch (Exception e) { //InstanceProvider.GetServiceLogger().AppendLine($"Error: {e.Message} {e.StackTrace}"); //InstanceProvider.GetServiceLogger().AppendLine($"Error: {e.Message}: {AvailBytes}, {byteCount}\n{e.StackTrace}"); } AvailBytes = client.Client.Available; if (InstanceProvider.GetClientService().ThreadState == ThreadState.Aborted) { keepalive = false; } } InstanceProvider.GetServiceLogger().AppendLine("IncomingListener thread exited."); }
internal JobDetails DeserializeJobDetails(string payload) { using (var parser = new JsonParser(payload)) { var job = parser.ParseNext(); if (!job.IsValidObject()) { throw new InvalidOperationException(); } return this.DeserializeJobDetails((JsonObject)job); } }
public JSONArrayIterator(String szData) { m_array = (List <Object>)JsonParser.JsonDecode(szData); m_nCurItem = 0; }
/// <summary> /// Return the level of matching to the given <paramref name="deviceDescription">device description</paramref>. /// </summary> /// <param name="deviceDescription"></param> /// <returns></returns> /// <remarks> /// The algorithm computes a score of how well the matcher matches the given description. For every property /// that is present on t /// </remarks> public float MatchPercentage(InputDeviceDescription deviceDescription) { if (empty) { return(0); } // Go through all patterns. Score is 0 if any of the patterns // doesn't match. var numPatterns = m_Patterns.Length; for (var i = 0; i < numPatterns; ++i) { var key = m_Patterns[i].Key; var pattern = m_Patterns[i].Value; if (key == kInterfaceKey) { if (string.IsNullOrEmpty(deviceDescription.interfaceName) || !MatchSingleProperty(pattern, deviceDescription.interfaceName)) { return(0); } } else if (key == kDeviceClassKey) { if (string.IsNullOrEmpty(deviceDescription.deviceClass) || !MatchSingleProperty(pattern, deviceDescription.deviceClass)) { return(0); } } else if (key == kManufacturerKey) { if (string.IsNullOrEmpty(deviceDescription.manufacturer) || !MatchSingleProperty(pattern, deviceDescription.manufacturer)) { return(0); } } else if (key == kProductKey) { if (string.IsNullOrEmpty(deviceDescription.product) || !MatchSingleProperty(pattern, deviceDescription.product)) { return(0); } } else if (key == kVersionKey) { if (string.IsNullOrEmpty(deviceDescription.version) || !MatchSingleProperty(pattern, deviceDescription.version)) { return(0); } } else { // Capabilities match. Take the key as a path into the JSON // object and match the value found at the given path. if (string.IsNullOrEmpty(deviceDescription.capabilities)) { return(0); } var graph = new JsonParser(deviceDescription.capabilities); if (!graph.NavigateToProperty(key.ToString()) || !graph.CurrentPropertyHasValueEqualTo(pattern)) { return(0); } } } // All patterns matched. Our score is determined by the number of properties // we matched against. var propertyCountInDescription = GetNumPropertiesIn(deviceDescription); var scorePerProperty = 1.0f / propertyCountInDescription; return(numPatterns * scorePerProperty); }
public virtual async Task<bool> Load(bool bRaiseError = true) { bool isLoaded = false; try { TapItHttpRequest req = new TapItHttpRequest(); string response = await req.HttpRequest(await GetAdSrvURL()); if (response == null) { Exception ex = new Exception( #if WINDOWS_PHONE TapItResource.ErrorResponse #elif WIN8 ResourceStrings.ErrorResponse #endif ); throw ex; } else if (response.Contains("error")) { Exception ex = new Exception(response); throw ex; } JsonParser jsnParser = new JsonParser(); _jsonResponse = jsnParser.ParseJson(response); isLoaded = true; } catch (Exception ex) { Debug.WriteLine("Exception in Load() :" + ex.Message); if (bRaiseError) OnError("Exception in Load()", ex); } return isLoaded; }
private static ConformanceResponse PerformRequest(ConformanceRequest request, TypeRegistry typeRegistry) { TestAllTypes message; try { switch (request.PayloadCase) { case ConformanceRequest.PayloadOneofCase.JsonPayload: var parser = new JsonParser(new JsonParser.Settings(20, typeRegistry)); message = parser.Parse<TestAllTypes>(request.JsonPayload); break; case ConformanceRequest.PayloadOneofCase.ProtobufPayload: message = TestAllTypes.Parser.ParseFrom(request.ProtobufPayload); break; default: throw new Exception("Unsupported request payload: " + request.PayloadCase); } } catch (InvalidProtocolBufferException e) { return new ConformanceResponse { ParseError = e.Message }; } catch (InvalidJsonException e) { return new ConformanceResponse { ParseError = e.Message }; } try { switch (request.RequestedOutputFormat) { case global::Conformance.WireFormat.JSON: var formatter = new JsonFormatter(new JsonFormatter.Settings(false, typeRegistry)); return new ConformanceResponse { JsonPayload = formatter.Format(message) }; case global::Conformance.WireFormat.PROTOBUF: return new ConformanceResponse { ProtobufPayload = message.ToByteString() }; default: throw new Exception("Unsupported request output format: " + request.PayloadCase); } } catch (InvalidOperationException e) { return new ConformanceResponse { SerializeError = e.Message }; } }
private IEnumerable<WabStorageAccountConfiguration> GetStorageAccountsFromJson(string value) { var storageAccounts = new List<WabStorageAccountConfiguration>(); var bytes = Encoding.UTF8.GetBytes(value); using (var memoryStream = new MemoryStream(bytes)) { var jsonParser = new JsonParser(memoryStream); var jsonItem = jsonParser.ParseNext(); var jsonArray = jsonItem as JsonArray; if (jsonArray == null) { return Enumerable.Empty<WabStorageAccountConfiguration>(); } for (int index = 0; index < jsonArray.Count(); index++) { var outputItem = jsonArray.GetIndex(index); var key = this.GetJsonStringValue(outputItem.GetProperty("Key")); var account = this.GetJsonStringValue(outputItem.GetProperty("AccountName")); var container = this.GetJsonStringValue(outputItem.GetProperty("Container")); storageAccounts.Add(new WabStorageAccountConfiguration(account, key, container)); } } return storageAccounts; }
public T DeserializeFrom <T>(string rStr) { JsonNode rJsonNode = JsonParser.Parse(rStr); return(rJsonNode.ToObject <T>()); }
static void Main(string[] args) { Console.WriteLine(TimePoint.FromTicks(16087186800000000).ToString()); return; #if true var h = new HashSet <TimePoint>(); var d = new Dictionary <TimePoint, int>(); h.Add(new TimePoint(2)); h.Add(new TimePoint(2)); d.Add(new TimePoint(302342342341), 2); d.Add(new TimePoint(302342342340), 3); foreach (var i in d) { Console.WriteLine(i.Key.ToString() + i.Value); } #elif true // Json var jsonObjectCollection = (JsonDataObject)JsonParser.Parse("{\"a\" : FalSe}"); Console.WriteLine(jsonObjectCollection["a"].GetBool()); //foreach (var i in jsonObjectCollection) //{ // var a = (JsonDataArray)i; // foreach (var jj in a) // { // var n = (JsonDataNumber)jj; // var Number = n.GetUInt32(); // Console.WriteLine(Number); // } //} return; string JsonStr = @" [3], [4] "; var j = JsonParser.Parse(JsonStr); Console.WriteLine(j.ToString()); // string JsonStr = @"{ // """" : """", // ""boolName"" : true, // ""boolName2"" : True, // ""boolName3"" : false, // ""boolName4"" : False, // ""name"" : ""string: ,@' t value"", // ""name2"":12.34 , // ""name3"" :5667, // ""objname"" :{}, // ""array"": [123,2234,""ok"",false,true,{},[]] //}"; // var j = JsonParser.Parse(JsonStr); // 중첩 컨테이너 가능할 때까지 아래 테스트 불가. //var pa = new SPoint[2]; //for (int i = 0; i < pa.Length; ++i) // pa[i] = new SPoint(1, 2); //j.Push("PointArray", pa); //var sa = new string[2]; //for (int i = 0; i < sa.Length; ++i) // sa[i] = i.ToString(); //j.Push("StringArray", sa); //var sl = new List<string>(); //for (int i = 0; i < 2; ++i) // sl.Add(i.ToString()); //j.Push("StringList", sl); //var hs = new HashSet<string>(); //for (int i = 0; i < 2; ++i) // hs.Add(i.ToString()); //j.Push("StringHashSet", hs); //var mss = new MultiSet<string>(); //for (int i = 0; i < 2; ++i) // mss.Add(i.ToString()); //j.Push("StringMultiSet", mss); //var pd = new Dictionary<string, SPoint>(); //for (int i = 0; i < 2; ++i) // pd.Add(i.ToString(), new SPoint(1, 1)); //j.Push("PointDictionary", pd); //var pmm = new CMultiMap<string, SPoint>(); //for (int i = 0; i < 2; ++i) // pmm.Add(i.ToString(), new SPoint(i, i)); //j.Push("PointMultiMap", pmm); //var l = new List<int>(); //l.Add(1000); //l.Add(2000); //j.Push("ListList", l); //var dd = new Dictionary<int, int>(); //dd.Add(1000, 1000); //dd.Add(2000, 2000); //var dhs = new HashSet<Dictionary<int, int>>(); //for (int i = 0; i < 2; ++i) // dhs.Add(dd); //j.Push("DictionaryHashSet", dhs); // Console.WriteLine(j.ToString()); #elif false // MultiMap int v; Console.WriteLine("MultiSet"); var ms = new MultiSet <int>(); ms.Add(3); ms.Add(3); ms.Add(3); ms.Add(2); ms.Add(4); Console.WriteLine("Count : " + ms.Count); ms.RemoveLast(); ms.RemoveLast(); ms.RemoveLast(); ms.RemoveLast(); Console.WriteLine("All Datas"); foreach (var i in ms) { Console.WriteLine(i); } Console.WriteLine("MultiMap"); var mm = new MultiMap <int, int>(); mm.Add(3, 4); mm.Add(3, 5); mm.Add(3, 6); mm.Add(2, 2); Console.WriteLine("All Datas : " + mm.Count); foreach (var i in mm) { Console.WriteLine(i); } Console.WriteLine("ToArray"); var a = mm.ToArray(3); foreach (var i in a) { Console.WriteLine(i); } var it = mm.First(); Console.WriteLine("First"); Console.WriteLine(it); mm.RemoveFirst(); Console.WriteLine("First Removed Count : " + mm.Count); foreach (var i in mm) { Console.WriteLine(i); } #elif true // Resize var l = new List <int>(); l.Resize(4); #endif }
private JsonObject parseMessagePayload(String messagePayload) { JsonParser parser = new JsonParser(new StringReader(messagePayload), true); return(parser.ParseObject()); }
public object DeserializeFrom(Type rType, string rStr) { JsonNode rJsonNode = JsonParser.Parse(rStr); return(rJsonNode.ToObject(rType)); }
public JsValue[] ParseParameters(string name, string[] arguments) { List<JsValue> parameters = new List<JsValue>(); int parameterNumber = 0; foreach (var json in arguments) { try { var input = new JsonParser(_engine).Parse(json); parameters.Add(input); parameterNumber++; } catch (Exception ex) { var details = string.Format(@"Error, unable to parse parameter '{0}': Parameter JSON {0}: ------ {1} ------ Message: {2} Function target: {3} In: {4} ", parameterNumber, json, ex.Message, name, _errorMessageContext + ":" + "Parse parameters" ); throw new JavascriptException(details, ex); } } return parameters.ToArray(); }
public void ComplexDictionary() { JsonParser jsonParser = new JsonParser(); object obj = jsonParser.Parse(_json3); Assert.IsInstanceOfType(obj,typeof(Dictionary<string,object>)); Dictionary<string, object> dic = (Dictionary<string, object>) obj; Assert.AreEqual(1, dic.Count); Assert.IsInstanceOfType(dic["menu"], typeof(Dictionary<string, object>)); Assert.AreEqual(2, ((Dictionary<string, object>)dic["menu"]).Count); }
private IEnumerable<KeyValuePair<string, string>> GetOutputItemsFromJson(string value) { var outputItems = new List<KeyValuePair<string, string>>(); var bytes = Encoding.UTF8.GetBytes(value); using (var memoryStream = new MemoryStream(bytes)) { var jsonParser = new JsonParser(memoryStream); var jsonItem = jsonParser.ParseNext(); var jsonArray = jsonItem as JsonArray; if (jsonArray == null) { return Enumerable.Empty<KeyValuePair<string, string>>(); } for (int index = 0; index < jsonArray.Count(); index++) { var outputItem = jsonArray.GetIndex(index); var keyProperty = this.GetJsonStringValue(outputItem.GetProperty("Key")); var valueProperty = this.GetJsonStringValue(outputItem.GetProperty("Value")); outputItems.Add(new KeyValuePair<string, string>(keyProperty, valueProperty)); } } return outputItems; }
public void SimpleTypedObject() { JsonParser jsonParser = new JsonParser(); Person person = jsonParser.Parse<Person>(_json); Assert.AreEqual("John Doe",person.name); Assert.AreEqual(4500.20m,person.salary); Assert.AreEqual(2,person.children.Length); Assert.AreEqual("Sarah", person.children[0]); Assert.AreEqual("Jessica", person.children[1]); }
public string SerializeToText(object rObj) { JsonNode rJsonNode = JsonParser.ToJsonNode(rObj); return(rJsonNode.ToString()); }
/// <summary> /// The SetJsonString. /// </summary> /// <param name="tmsg">The tmsg<see cref="DealMessage"/>.</param> /// <returns>The <see cref="string"/>.</returns> public static string SetJsonString(this DealMessage tmsg) { IDictionary <string, object> toJson = tmsg.SetJsonBag(); return(JsonParser.ToJson(toJson)); }
public void EmptyArray() { JsonParser parser = new JsonParser(); object items = ((Dictionary<string,object>) parser.Parse(@"{ ""array"" : [] }"))["array"]; Assert.IsInstanceOfType(items,typeof(object[])); Assert.AreEqual(0,((object[])items).Length); }
public CommunicationService(string address) { jsonParser = new JsonParser(); this.Address = address; }
public void TestEscapes() { JsonParser parser = new JsonParser(); object item = ((Dictionary<string, object>)parser.Parse(@"{ ""obj"" : ""\n"" }"))["obj"]; Assert.IsInstanceOfType(item,typeof(string)); Assert.AreEqual("\n", item); item = ((Dictionary<string, object>)parser.Parse(@"{ ""obj"" : ""\t"" }"))["obj"]; Assert.IsInstanceOfType(item,typeof(string)); Assert.AreEqual("\t", item); item = ((Dictionary<string, object>)parser.Parse(@"{ ""obj"" : ""\\"" }"))["obj"]; Assert.IsInstanceOfType(item,typeof(string)); Assert.AreEqual(@"\", item); item = ((Dictionary<string, object>)parser.Parse(@"{ ""obj"" : ""\u00aa"" }"))["obj"]; Assert.IsInstanceOfType(item,typeof(string)); Assert.AreEqual("\u00aa", item); }
public void Setup() { _parser = new JsonParser(); }