/// <summary> /// Requests the latest live feed of the user and a random Rayz from the list /// Random is latest /// </summary> public async Task <IJSonObject> GetLiveFeedRandom() { try { var reader = new JSonReader(); var response = await _client.GetAsync(new Uri(ServerBaseUri, "/user/" + _deviceId + "/livefeed/random")); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
/// <summary> /// Requests the live feed settings values for the application /// </summary> public async Task <IJSonObject> GetLiveSettings() { try { var reader = new JSonReader(); var response = await _client.GetAsync(new Uri(ServerBaseUri, "/settings")); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
/// <summary> /// Reports a RayzReply /// </summary> /// <param name="rayzReplyId"> RayzReply ID </param> public async Task <IJSonObject> ReportRayzReply(String rayzReplyId) { try { var writer = new JSonWriter(true); var reader = new JSonReader(); writer.WriteObjectBegin(); writer.WriteMember("userId", _deviceId); writer.WriteMember("rayzReplyId", rayzReplyId); writer.WriteObjectEnd(); var json = new StringContent(writer.ToString()); json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var response = await _client.PostAsync(new Uri(ServerBaseUri, "/rayz/reply/report"), json); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
public void ParseNumberWithForcedFormat() { var reader = new JSonReader(); var result1 = reader.ReadAsJSonObject("[12, 13, 14]", JSonReaderNumberFormat.AsInt32); var result2 = reader.ReadAsJSonObject("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64); var result3 = reader.ReadAsJSonObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble); var result4 = reader.ReadAsJSonObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal); var result5 = reader.Read("[12, 13, 14]", JSonReaderNumberFormat.AsInt32); var result6 = reader.Read("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64); var result7 = reader.Read("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble); var result8 = reader.Read("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal); var result9 = reader.ReadAsJSonMutableObject("[12, 13, 14]", JSonReaderNumberFormat.AsInt32); var result10 = reader.ReadAsJSonMutableObject("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64); var result11 = reader.ReadAsJSonMutableObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble); var result12 = reader.ReadAsJSonMutableObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal); Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.IsNotNull(result4); Assert.IsNotNull(result5); Assert.IsNotNull(result6); Assert.IsNotNull(result7); Assert.IsNotNull(result8); Assert.IsNotNull(result9); Assert.IsNotNull(result10); Assert.IsNotNull(result11); Assert.IsNotNull(result12); }
private void LoadJsonData() { var jsonReader = new JSonReader(); _jsonAccountData = jsonReader.ReadAsJSonObject(File.ReadAllText(@"Resources\accounts.json")); _jsonBalanceData = jsonReader.ReadAsJSonObject(File.ReadAllText(@"Resources\accountbalances.json")); }
/// <summary> /// Creates a new RayzReply /// </summary> /// <param name="rayzId"> Rayz ID </param> /// <param name="rayzReply"> The RayzReply message </param> /// <param name="attachments"> The RayzReply Attachments </param> public async Task <IJSonObject> NewRayzReply(String rayzId, String rayzReply, ObservableCollection <RayzItAttachment> attachments) { try { var content = new MultipartFormDataContent(); var writer = new JSonWriter(true); var reader = new JSonReader(); // PLAY PROBLEM foreach (var param in content.Headers.ContentType.Parameters.Where(param => param.Name.Equals("boundary"))) { param.Value = param.Value.Replace("\"", String.Empty); } writer.WriteObjectBegin(); writer.WriteMember("userId", _deviceId); writer.WriteMember("rayzId", rayzId); writer.WriteMember("rayzReplyMessage", rayzReply); writer.WriteObjectEnd(); var json = new StringContent(writer.ToString()); content.Add(json, "\"json\""); foreach (var a in attachments) { var fileContent = new StreamContent(new MemoryStream(a.FileBody)); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"attachment\"", FileName = "\"attachment.file\"" }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(a.ContType); content.Add(fileContent); } var response = await _client.PostAsync(new Uri(ServerBaseUri, "/rayz/reply"), content); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
public static IJSonObject ToJSon(this string value) { JSonReader reader = new JSonReader(); try { IJSonObject data = reader.ReadAsJSonObject(value); return(data); } catch (JSonReaderException) { return(reader.ReadAsJSonObject(ERROR_INVALID_JSON)); } }
public void ParseChineseTextWithEmbeddedArray() { var jsonText = LoadTestInputFile("chinese_encoding.json"); var reader = new JSonReader(jsonText); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result); var internalData = reader.ReadAsJSonObject(result["DataObject"].StringValue); Assert.IsNotNull(internalData); Assert.AreEqual(2, internalData.Count); Assert.AreEqual("业务员", internalData[0]["EmployeeType"].StringValue); }
public void ConvertImmutableJSonObjectToMutableAndUpdateIt() { var jsonText = "{ \"a\": 1, \"b\": 2, \"c\": [1,2,3,4] }"; var reader = new JSonReader(jsonText); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result, "Invalid data read!"); Assert.AreEqual(1, result["a"].Int32Value, "Unexpected value for field 'a'."); var clone = result.CreateMutableClone(); Assert.IsNotNull(clone, "Unexpected null clone!"); Assert.AreEqual(1, clone["a"].Int32Value, "Unexpected value for clonned field 'a'."); Assert.IsTrue(clone["a"].IsMutable, "Value should be mutable!"); clone["a"].AsMutable.SetValue(3); clone.SetValue("b", 4); clone["c"].AsMutable.SetValueAt(2, 55); Assert.AreEqual(3, clone["a"].Int32Value, "Expected value to be updated for field 'a'!"); Assert.AreEqual(4, clone["b"].Int32Value, "Expected value to be updated for field 'b'!"); Assert.AreEqual(55, clone["c"][2].Int32Value, "Expected array item to be updated!"); // verify, that original object was left intact: Assert.AreEqual(1, result["a"].Int32Value, "Unexpected update!"); Assert.AreEqual(2, result["b"].Int32Value, "Unexpected update!"); Assert.AreEqual(3, result["c"][2].Int32Value, "Unexpected update!"); }
public void ParseNullKeyword() { var reader = new JSonReader(" null"); var result = reader.ReadAsJSonObject(); Assert.AreEqual(result.StringValue, null, "Expected a null string!"); }
public void TestMissingMember() { var reader = new JSonReader("{ \"Name\": \"Jan\" }"); var result = reader.ReadAsJSonObject().ToObjectValue <SampleAttributedClass>(); Assert.IsNotNull(result); }
public void TestSerializeAndDeserializeViaSimpleAttributes() { SampleAttributedClass o1 = new SampleAttributedClass("Paweł", 20); writer.Write(o1); var result = writer.ToString(); Assert.IsNotNull(result, "Expected some serialized data"); Assert.IsFalse(result.Contains(SampleAttributedClass.Text), "Unexpected 'const' field in serialized output"); Assert.IsTrue(result.Contains("StaticSampleField"), "Expected static field in output"); SampleAttributedClass.StaticSampleField = true; var reader = new JSonReader(writer.ToString()); var o2 = reader.ReadAsJSonObject().ToObjectValue <SampleAttributedClass>(); Assert.IsNotNull(o2, "Correct value expected"); Assert.AreEqual(o2.Name, o1.Name, "Name is not equal expected value"); Assert.AreEqual(o2.Age, o1.Age, "Age is not equal expected value"); Assert.AreEqual(o2.Address, "default", "Address should be equal to default value"); // try to load array of elements: reader = new JSonReader("[" + result + "]"); var o3 = reader.ReadAsJSonObject().ToObjectValue <IList <SampleAttributedClass> >(); Assert.IsNotNull(o3, "Expected data to be read"); o2 = o3[0]; Assert.IsNotNull(o2, "Correct value expected"); Assert.AreEqual(o2.Name, o1.Name, "Name is not equal expected value"); Assert.AreEqual(o2.Age, o1.Age, "Age is not equal expected value"); Assert.AreEqual(o2.Address, "default", "Address should be equal to default value"); }
public async Task <IJSonObject> CheckRayzReplies(string rayzid, IEnumerable <string> rayzsList) { try { var writer = new JSonWriter(true); var reader = new JSonReader(); writer.WriteObjectBegin(); writer.WriteMember("userId", _deviceId); writer.WriteMember("rayzId", rayzid); writer.WriteMember("rayzReplyIds"); writer.WriteArrayBegin(); //Group up the records in the collection foreach (var record in rayzsList) { writer.WriteValue(record); } writer.WriteArrayEnd(); writer.WriteObjectEnd(); var json = new StringContent(writer.ToString()); json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var response = await _client.PostAsync(new Uri(ServerBaseUri, "/rayz/reply/check"), json); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
public void ParseDecimalGivenAsString2() { var reader = new JSonReader("\"12312.3456\""); var result = reader.ReadAsJSonObject().DecimalValue; AssertExt.IsInstanceOf <decimal>(result, "Item should be a number"); Assert.AreEqual(result, new Decimal(12312.3456)); }
public void ParseDateWithoutTimeAsUnspecified() { var reader = new JSonReader("\"1999-01-07\""); var item = reader.ReadAsJSonObject(); var date = item.DateTimeValue; Assert.AreEqual(new DateTime(1999, 01, 07, 0, 0, 0, DateTimeKind.Unspecified), date); }
public void ParseISODateWithoutTimeZone() { var reader = new JSonReader("\"2012-05-17 09:58:33\""); var item = reader.ReadAsJSonObject(); var date = item.DateTimeValue; Assert.AreEqual(new DateTime(2012, 05, 17, 09, 58, 33, DateTimeKind.Local), date); }
public void ParseISODateWithTimeZone() { var reader = new JSonReader("\"2012-06-16T21:09:45+00:00\""); var item = reader.ReadAsJSonObject(); var date = item.DateTimeValue; Assert.AreEqual(new DateTime(2012, 06, 16, 21, 9, 45, DateTimeKind.Utc).ToLocalTime(), date); }
public void ParseNumberWithDecimalForced_AndCheckItemType() { var reader = new JSonReader((ulong.MaxValue + 1d).ToString(CultureInfo.InvariantCulture)); var result = reader.ReadAsJSonObject(JSonReaderNumberFormat.AsDecimal); Assert.IsNotNull(result); Assert.IsTrue(result.GetType().Name.Contains("DecimalDecimal")); }
public void ToStringWithInvalidFormat() { var reader = new JSonReader("[1, 2, 3, [\"a\", \"b\", \"c\", [4, 5, 6, [{\"f\": 1, \"x\": 2}]]]]"); var data = reader.ReadAsJSonObject(); Assert.IsNotNull(data); data.ToString("xxl"); }
public void ParseTrueKeyword() { var reader = new JSonReader(" true "); var result = reader.ReadAsJSonObject(); Assert.AreEqual("true", result.StringValue, "Expected 'true' string returned"); Assert.AreEqual(true, result.BooleanValue, "Expected boolean true value"); Assert.AreEqual(1, result.DoubleValue, "Expected non zero value"); }
public void ParseDataTimeUtc() { DateTime date = new DateTime(2012, 5, 14, 11, 22, 33, DateTimeKind.Utc); var reader = new JSonReader(String.Format("\"{0}\"", date.ToString("u"))); var result = reader.ReadAsJSonObject().DateTimeValue.ToUniversalTime(); AssertExt.IsInstanceOf <DateTime>(result, "Item should be a DataTime"); Assert.AreEqual(result, date); }
/// <summary> /// Makes a Re-Rayz Request /// </summary> /// <param name="rayzId"> Rayz ID </param> /// <param name="latitude"> Latitude Coordinate </param> /// <param name="longitude"> Longitude Coordinate </param> /// <param name="accuracy"> Accuracy of the user's position in meters </param> /// <param name="maxDistance"> Max Rayz Distance - NOT USED </param> public async Task <IJSonObject> ReRayz(String rayzId, String latitude, String longitude, String accuracy, String maxDistance) { try { var writer = new JSonWriter(true); var reader = new JSonReader(); // Make sure that lat and long are dot separated latitude = latitude.Replace(@",", @"."); longitude = longitude.Replace(@",", @"."); writer.WriteObjectBegin(); writer.WriteMember("userId", _deviceId); writer.WriteMember("rayzId", rayzId); writer.WriteMember("latitude", latitude); writer.WriteMember("longitude", longitude); writer.WriteMember("accuracy", accuracy); writer.WriteMember("maxDistance", maxDistance); writer.WriteObjectEnd(); var json = new StringContent(writer.ToString()); json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var response = await _client.PostAsync(new Uri(ServerBaseUri, "/rayz/rerayz"), json); var cr = CheckResponse(response); if (cr != null) { var creply = reader.ReadAsJSonObject(cr); return(creply); } var r = await response.Content.ReadAsStringAsync(); var reply = reader.ReadAsJSonObject(r); return(reply); } catch (Exception) { return(null); } }
public void ParseBayeuxConnectResponse() { var reader = new JSonReader("[{\"channel\":\"/meta/connect\",\"advice\":{\"reconnect\":\"retry\",\"interval\":0,\"timeout\":20000},\"successful\":true,\"id\":\"1\"}]"); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result, "Invalid parsed object!"); int timeout = result[0]["advice"]["timeout"].Int32Value; Assert.AreEqual(20000, timeout, "Invalid timeout value!"); }
public void TryToUpdateImmutableJSonObject() { var jsonText = "{ \"a\": 1, \"b\": 2 }"; var reader = new JSonReader(jsonText); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result, "Invalid data read!"); Assert.AreEqual(1, result["a"].Int32Value, "Unexpected value for field 'a'."); result.AsMutable.SetValue("a", 3); }
// Obtem o resultado da conexao private void handleConnection(WWW conn, string id, object state, byte[] form_data, Hashtable headers) { // Verifica se houve erro if (conn.error != null) { if (url.Contains(Flow.URL_BASE) && url.EndsWith(".picture.php")) { return; } Debug.Log(url); Debug.Log("Internal server error to url (" + url + "): " + conn.error); sendToCallbackPersistent(conn.error, conn, state, id, conn.url, form_data, headers); return; } // Verifica se pediu senha try { JSonReader reader = new JSonReader(); IJSonObject data = reader.ReadAsJSonObject(conn.text); if (data != null && data.Contains("ask")) { // Caso peca senha, avisa o erro if (data["ask"].ToString() == "password") { sendToCallbackPersistent(DEFAULT_ERROR_MESSAGE + "r", null, state, id, conn.url, form_data, headers); } // Obtem o token do Facebook, caso necessario else if (data["ask"].ToString() == "fb_token") { GameFacebook facebook = new GameFacebook(); facebook.login(); sendToCallbackPersistent(DEFAULT_FB_TOKEN_ERROR_MESSAGE, null, state, id, conn.url, form_data, headers); } // Refaz a conexao caso necessario e possivel //if (redo && GameGUI.components != null) GameGUI.components.StartCoroutine(startConnection(form, state, false)); //else Application.LoadLevel(GameGUI.components.login_scene); return; } } catch (JSonReaderException) { } sendToCallbackPersistent(conn.error, conn, state, id, conn.url, form_data, headers); }
public void ParseExplicitDate_Varian1() { var reader = new JSonReader("\"\\/ DATE (1920,12,31)\\/\""); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result); var date = result.DateTimeValue.ToUniversalTime(); Assert.AreEqual(1920, date.Year); Assert.AreEqual(12, date.Month); Assert.AreEqual(31, date.Day); }
public void ParseDate1970_Variant1() { var reader = new JSonReader("\"/DATE(0)/\""); var result = reader.ReadAsJSonObject(); Assert.IsNotNull(result); var date = result.DateTimeValue.ToUniversalTime(); Assert.AreEqual(1970, date.Year); Assert.AreEqual(1, date.Month); Assert.AreEqual(1, date.Day); }
public void ParseToJSon() { const string jsonText = "[{\"minimumVersion\":\"1.0\",\"type\": null,\"channel\":\"\\/meta\\/handshake\",\"supportedConnectionTypes\":[\"request-response\"],\"successful\":true}]"; var reader = new JSonReader(jsonText); var result = reader.ReadAsJSonObject(); Assert.AreEqual("/meta/handshake", result[0]["channel"].StringValue, "Invalid channel"); Assert.IsTrue(result[0]["type"].IsNull, "Type should be null"); Assert.AreEqual(1, result[0]["supportedConnectionTypes"].Count, "Supported types are an array with 1 element"); Assert.AreEqual(1.0, result[0]["minimumVersion"].DoubleValue, "Current version is 1.0"); Assert.IsTrue(result[0]["successful"].IsTrue, "Operation finished with success!"); }
public void ParseAdvancedGuidArray() { var jsonText = LoadTestInputFile("guid.json"); var watchReader = Stopwatch.StartNew(); var reader = new JSonReader(jsonText); var result = reader.ReadAsJSonObject(); watchReader.Stop(); Assert.IsNotNull(result); AssertExt.IsInstanceOf <Guid>(result[0].GuidValue, "Read element should be Guid"); Console.WriteLine("Parsing taken: {0}", watchReader.Elapsed); }
/// <summary> /// Handles the messages from server to the user's subscribed channel and calls the appropriate event handler for further processing /// Supports 3 types of messages: /// Rayz Received /// Rayz Reply Received /// Rayz Power Updates /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LogChatEventReceived(object sender, BayeuxConnectionEventArgs e) { var reader = new JSonReader(); if (e.Message != null) { var reply = reader.ReadAsJSonObject(e.Message.ToString()); //System.Diagnostics.Debug.WriteLine(_count++); if (reply.ObjectItems != null) { foreach (var objItem in reply.ObjectItems) { if (objItem.Key != "data") { continue; } if (objItem.Value != null) { var type = objItem.Value["mtype"].ToString(); switch (type) { case "rayz": if (RayzMessageReceived != null) { RayzMessageReceived(this, objItem.Value); } break; case "rayz_reply": if (RayzReplyMessageReceived != null) { RayzReplyMessageReceived(this, objItem.Value); } break; case "power": if (PowerUpdateReceived != null) { PowerUpdateReceived(this, objItem.Value); } break; } } } } } }