public static int GetInt(JsonValue value) { try { int temp = 0; if (value != null && !string.IsNullOrEmpty(value.ToString())) { int.TryParse(value.ToString(), out temp); } return temp; } catch { return 0; } }
/*private void ParseAndDisplay (JsonValue json, ListView workshopList) { string jsonString = json.ToString(); WorkshopSetResult root = JsonConvert.DeserializeObject<WorkshopSetResult> (jsonString); workshopSets = root.Results; workshopList = FindViewById<ListView> (Resource.Id.workshopList); WorkshopSetAdapter adapter = new WorkshopSetAdapter (this, workshopSets); workshopList.Adapter = adapter; //workshopList.ItemClick += workshopList_ItemClick; workshopList.ItemClick += async (object sender, AdapterView.ItemClickEventArgs e) => { int clickedID = workshopSets [e.Position].id; string url = String.Format ("http://uts-helps-07.cloudapp.net/api/workshop/search?workshopSetID={0}", clickedID); Console.WriteLine("Clicked ID is {0}", clickedID); Console.WriteLine(url); JsonValue j = await FetchWorkshopAsync (url); string jObject = j.ToString(); Intent intent = new Intent (this, typeof(WorkshopActivity)); //intent.PutExtra ("WorkshopSetID", clickedID); intent.PutExtra("JsonValue", jObject); this.StartActivity (intent); }; }
private object GetJsonValue(JsonValue member) { object result = null; if (member.JsonType == JsonType.Array) { var array = member as JsonArray; if (array.Any()) { if (array.First().JsonType == JsonType.Object || array.First().JsonType == JsonType.Array) result = array.Select(x => new DynamicJsonObject(x as JsonObject)).ToArray(); else result = array.Select(x => GetJsonValue(x)).ToArray(); } else result = member; } else if (member.JsonType == JsonType.Object) { return new DynamicJsonObject(member as JsonObject); } else if (member.JsonType == JsonType.Boolean) return (bool)member; else if (member.JsonType == JsonType.Number) { string s = member.ToString(); int i; if (int.TryParse(s, out i)) return i; else return double.Parse(s); } else return (string)member; return result; }
private string displayString(JsonValue input) { string s = input.ToString (); int l = s.Length-2; string output = s.Substring(1, l); return output; }
void Populate (JsonValue json, RootElement root, JsonValue data) { if (json.ContainsKey(Constants.Title)) root.Caption = json[Constants.Title]; JsonValue jsonRoot = null; try { jsonRoot = json[Constants.Root]; } catch (Exception){ Console.WriteLine("Bad JSON: could not find the root element - "+json.ToString()) ; return; } if (json.ContainsKey(Constants.DataRoot)){ var dataroot = json[Constants.DataRoot].CleanString(); if (data!=null && data.ContainsKey(dataroot)) data = data[dataroot]; } foreach (JsonObject section in jsonRoot){ var sec = new FormSectionBuilder(this._controller).Build(section, data); foreach (var el in sec.Elements) { if (!string.IsNullOrEmpty(el.ID) && !_elements.ContainsKey(el.ID)) _elements.Add(el.ID, el); } root.Add(sec); } }
public static string GetString(JsonValue value) { try { string temp = string.Empty; if (value != null && !string.IsNullOrEmpty(value.ToString())) { temp = value.ToString().TrimStart('"').TrimEnd('"'); } return temp; } catch { return string.Empty; } }
private static object[] CovertToObjectArray(System.Json.JsonValue row) { object[] _objAry = new object[row.Count]; for (int _i = 0, _iCnt = row.Count; _i < _iCnt; _i++) { if (null != row[_i]) { System.Json.JsonValue _objRow = row[_i]; switch (_objRow.JsonType) { case System.Json.JsonType.Boolean: _objAry[_i] = Convert.ToBoolean(_objRow.ToString()); break; case System.Json.JsonType.String: int length = _objRow.ToString().Length - 2; _objAry[_i] = _objRow.ToString().Substring(1, length); break; case System.Json.JsonType.Number: _objAry[_i] = Convert.ToDecimal(_objRow.ToString()); break; case System.Json.JsonType.Object: _objAry[_i] = "键:值"; break; case System.Json.JsonType.Array: _objAry[_i] = "数组"; break; } } else { _objAry[_i] = null; } //_objAry[_i] = string.Format("{0}", _objRow); } return(_objAry); }
public Tweet(JsonValue source) { this.SourceString = source.ToString (); var result = source; var text = result ["text"]; var date = result ["created_at"]; var userInfo = result ["user"]; var user = JsonValue.Parse (userInfo.ToString ()); var name = user ["name"]; var screen_name = user ["screen_name"]; var imageUrl = user ["profile_image_url"]; this.StatusText = displayString (text); this.StatusDate = displayString (date); this.UserName = displayString (name); this.ScreenName = displayString (screen_name); downloadImage (displayString (imageUrl)); }
public static Gym[] InstatiateManyFromGeoJson(JsonValue json) { var strJson = json.ToString(); JObject geo = JObject.Parse(strJson); if (((JArray )geo["results"]).Count > 0) { var results = (JArray) geo["results"]; var gyms = new List<Gym>(); foreach (var data in results) { gyms.Add(InstatiateFromGeoJson(data)); } return gyms.ToArray(); } return null; }
public static void ConfigureAnonymousVectorLayers(this MapView map, JsonValue config) { // Use the Maps service to configure layers. // Note that this must be done in a separate thread on Android, // as Maps API requires connecting to server which is not nice to do in main thread. System.Threading.Tasks.Task.Run(delegate { CartoMapsService service = new CartoMapsService(); service.Username = "******"; // Use VectorLayers service.DefaultVectorLayerMode = true; service.Interactive = true; LayerVector layers = service.BuildMap(Variant.FromString(config.ToString())); for (int i = 0; i < layers.Count; i++) { map.Layers.Add(layers[i]); } }); }
void Populate (JsonValue json, RootElement root, JsonValue data) { if (json.ContainsKey("title")) root.Caption = json["title"]; JsonValue jsonRoot = null; try { jsonRoot = json["root"]; } catch (Exception){ Console.WriteLine("Bad JSON: could not find the root element - "+json.ToString()) ; return; } foreach (JsonObject section in jsonRoot){ var sec = new Section(section.s("caption"), section.s("footer")); if (section.ContainsKey("elements")){ foreach (JsonObject elem in section["elements"]) { var dataForElement = data; var bindExpression = elem.s("bind"); if (bindExpression!=null) { try { if (data!=null && data.JsonType==JsonType.Object){ var bind = elem.s("bind"); if (data != null && !string.IsNullOrEmpty(bind) && data.ContainsKey(bind)) { dataForElement = data[bind]; } } else if (bindExpression.StartsWith("#")) { dataForElement = _controller.GetValue(bindExpression.Replace("#", "")); } } catch (Exception){ Console.WriteLine("Exception when binding element " + elem.ToString()); } } _parseElement(elem, sec, dataForElement); } } else if (section.ContainsKey("iterate") && data != null){ string iterationname = section["iterate"]; string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty"; var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonArray)data : (JsonArray)data[iterationname]; var template = (JsonObject)section["template"]; var items = iterationdata.ToList(); if (items.Count>0) { foreach(JsonValue v in items){ _parseElement(template, sec, v); } } else { sec.Add(new EmptyListElement(emptyMessage)); } } else if (section.ContainsKey("iterateproperties") && data != null){ string iterationname = section["iterateproperties"]; string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty"; var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonObject)data : (JsonObject)data[iterationname]; var template = (JsonObject)section["template"]; var items = iterationdata.Keys; if (items.Count>0) { foreach(string v in items){ var obj = new JsonObject(); obj.Add(v, iterationdata[v]); _parseElement(template, sec, obj); } } else { sec.Add(new EmptyListElement(emptyMessage)); } } root.Add(sec); } }
private void DoRoundTripCasting(JsonValue jo, Type type) { bool result = false; // Casting if (jo.JsonType == JsonType.String) { JsonValue jstr = (string)jo; if (type == typeof(DateTime)) { Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(DateTimeOffset)) { Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(Guid)) { Log.Info("{0} Value:{1}", type.Name, (Guid)jstr); } else if (type == typeof(char)) { Log.Info("{0} Value:{1}", type.Name, (char)jstr); } else if (type == typeof(Uri)) { Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri); } else { Log.Info("{0} Value:{1}", type.Name, (string)jstr); } if (jo.ToString() == jstr.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Object) { JsonObject jobj = new JsonObject((JsonObject)jo); if (jo.ToString() == jobj.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Number) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Boolean) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, (bool)jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } Assert.True(result); }
/// <constructor /> public JsonContent(JsonValue json) : base(json.ToString(), Encoding.UTF8, MediaType.Json) { }
public string convertAndInitializeToString(JsonValue value) { return (value == null) ? "" : value.ToString().Replace("\"", ""); }
async static Task<JsonValue> SendData (string method, string baseUrl, string api, JsonValue json, Dictionary<string, string> headers) //, Cookie cookie = null) { JsonObject result = new JsonObject (); Stream dataStream; HttpWebResponse response; byte[] byteArray = null; if (json != null) { byteArray = Encoding.UTF8.GetBytes (json.ToString ()); } else { byteArray = new byte[0]; } string url = baseUrl + api; Uri uri = new Uri (url); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (uri); if (json != null) { request.ContentType = "application/json"; } request.Method = method; request.ContentLength = byteArray.Length; request.Timeout = TIMEOUT_IN_MILLISECONDS; if (request.Method == "POST") { request.AllowAutoRedirect = false; if (json != null) { request.Accept = "application/json"; } } if (headers != null) { foreach (var kvPair in headers) { request.Headers.Set (kvPair.Key, kvPair.Value); } } // if (cookie == null) { // request.CookieContainer = new CookieContainer (); // request.CookieContainer.Add (uri, new CookieCollection ()); // } else { // CookieContainer cookieContainer = new CookieContainer(); // cookie.Domain = uri.Host; // cookieContainer.Add(cookie); // request.CookieContainer = cookieContainer; // } try { dataStream = await request.GetRequestStreamAsync ();//.WithTimeout(TIMEOUT_IN_MILLISECONDS); } catch (Exception e) { // result [Codec.EXCEPTION] = Response.ErrorCreatingStream; // if (IsNameResolutionFailure (e) || IsNetworkingUnreachable (e)) { // result [Codec.MESSAGE] = COULDNOTCONNECT + INTERNETAVAILABILITY; // } else { // result [Codec.MESSAGE] = e.Message; // } Console.WriteLine ("# Exception GetRequestStreamAsync: " + e); return result; } try { if (json != null) { await dataStream.WriteAsync (byteArray, 0, byteArray.Length); } } catch (Exception e) { // result [Codec.EXCEPTION] = Response.ErrorWritingStream; // result [Codec.MESSAGE] = e.Message; Console.WriteLine ("# Exception dataStream.WriteAsync: " + e); return result; } try { response = (HttpWebResponse)await request.GetResponseAsync ();//.WithTimeout (TIMEOUT_IN_MILLISECONDS); } catch (WebException e) { response = (HttpWebResponse)e.Response; // int statusCode = 32000; // string message = ""; // if (response != null) { // statusCode = (int)response.StatusCode; // message = StreamToString (response.GetResponseStream ()); // } // result [Codec.EXCEPTION] = statusCode; // result [Codec.MESSAGE] = message; Console.WriteLine ("# WebException request.GetResponseAsync: " + e); return result; } catch (Exception e) { // result [Codec.EXCEPTION] = Response.ErrorGettingResponse; // result [Codec.MESSAGE] = e.Message; Console.WriteLine ("# Exception request.GetResponseAsync: " + e); return result; } if (response == null) { // result [Codec.EXCEPTION] = Response.ErrorGettingResponse; Console.WriteLine ("# Exception response == null"); return result; } if (response.StatusCode != HttpStatusCode.OK) { // result [Codec.EXCEPTION] = ((int)response.StatusCode).ToString (); // result [Codec.MESSAGE] = response.StatusDescription; Console.WriteLine ("# Exception response.StatusCode != HttpStatusCode.OK"); return result; } var stream = response.GetResponseStream (); var returnValue = StreamToString (stream); try { JsonValue parsedJson = JsonObject.Parse (returnValue); // if (cookie == null) { // foreach (Cookie responseCookie in response.Cookies) { // parsedJson[responseCookie.Name] = responseCookie.Value; // } // } return parsedJson; } catch (Exception e) { // result [Codec.EXCEPTION] = Response.ErrorParsingResponse; // result [Codec.MESSAGE] = ERRORPARSINGRESPONSE; Console.WriteLine ("# Exception JsonObject.Parse: " + e); return result; } }
/// <summary> /// Parses a JsonValue to int. /// </summary> /// <returns>An int with same value as the JsonValue.</returns> /// <param name="value">Value.</param> private int parseToInt(JsonValue value) { try { string strVal = value.ToString(); return int.Parse(strVal); } catch (Exception e) { LatestError = "Failed to parse event-id" + e.Message; return -1; } }
public DateTime convertAndInitializeToDateTime(JsonValue value) { return (value == null) ? new DateTime() : Convert.ToDateTime(value.ToString().Replace("\"", "")); }
public int convertAndInitializeToInt(JsonValue value) { return (value == null || value.ToString().Replace("\"", "") == "") ? 0 : Convert.ToInt32(value.ToString().Replace("\"", "")); }
public JsonContent(JsonValue content) : base(content.ToString(), Encoding.UTF8, "application/json") { }
/// <summary> /// Recursively constructs this JSONObject /// </summary> private static JSONObject Create(JsonValue o) { JSONObject obj = new JSONObject(); if (o is JsonObject) { } foreach (JsonObject a in o) { } if (o is JsonArray) { JsonArray objArray = (JsonArray)o; obj._arrayData = new JSONObject[objArray.Count]; for (int i = 0; i < obj._arrayData.Length; ++i) { obj._arrayData[i] = Create(objArray[i]); } } /* else if (o is Dictionary<string, object>) { obj._dictData = new Dictionary<string, JSONObject>(); var dict = (Dictionary<string, object>)o; foreach (string key in dict.Keys) { obj._dictData[key] = Create((JsonValue)dict[key]); } } */ else if (o != null) // o is a scalar { obj._stringData = o.ToString(); } return obj; }
/// <summary> /// Handle an unknown event (default) /// </summary> /// <param name="payload">JSON payload</param> public void HandleDefault(JsonValue json) { response.Write(String.Format("Unknown event. Raw data: {0}", json.ToString())); response.StatusCode = 500; }
public void EscapedCharacters() { string str = null; JsonValue value = null; str = (string)value; Assert.Null(str); value = "abc\b\t\r\u1234\uDC80\uDB11def\\\0ghi"; str = (string)value; Assert.Equal("\"abc\\u0008\\u0009\\u000d\u1234\\udc80\\udb11def\\\\\\u0000ghi\"", value.ToString()); value = '\u0000'; str = (string)value; Assert.Equal("\u0000", str); }
public void ToStringTest() { JsonArray target; JsonValue item1 = AnyInstance.AnyJsonValue1; JsonValue item2 = null; JsonValue item3 = AnyInstance.AnyJsonValue2; target = new JsonArray(item1, item2, item3); string expected = String.Format(CultureInfo.InvariantCulture, "[{0},null,{1}]", item1.ToString(), item3.ToString()); Assert.Equal(expected, target.ToString()); string json = "[\r\n \"hello\",\r\n null,\r\n [\r\n 1,\r\n 2,\r\n 3\r\n ]\r\n]"; target = JsonValue.Parse(json) as JsonArray; Assert.Equal <string>(json.Replace("\r\n", "").Replace(" ", ""), target.ToString()); }
public static DateTime? JsonToTime(JsonValue json) { //"/Date(1311694174896+0000)/" string jsonStr = json.ToString(); jsonStr = jsonStr.Substring(7); jsonStr = jsonStr.Substring(0, jsonStr.IndexOf("+")); double ms = 0; if (double.TryParse(jsonStr, out ms)) { return unixEpoch.AddMilliseconds(ms); } return null; }
public MockMessageHandler(HttpStatusCode code, JsonValue responseJson) : this(code, responseJson.ToString(), "application/json") { }
private static JsonValue ValidateSerialization(JsonValue beforeSerialization) { Assert.NotNull(beforeSerialization); NetDataContractSerializer serializer = new NetDataContractSerializer(); using (MemoryStream memStream = new MemoryStream()) { serializer.Serialize(memStream, beforeSerialization); memStream.Position = 0; JsonValue afterDeserialization = (JsonValue)serializer.Deserialize(memStream); Assert.Equal(beforeSerialization.ToString(), afterDeserialization.ToString()); return afterDeserialization; } }
public static Cart Deserialize(JsonValue json) { String data = json.ToString (); return (Cart)Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(Cart)); }
private void DoRoundTripCasting(JsonValue jo, Type type) { bool result = false; // Casting if (jo.JsonType == JsonType.String) { JsonValue jstr = (string)jo; if (type == typeof(DateTime)) { Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(DateTimeOffset)) { Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(Guid)) { Log.Info("{0} Value:{1}", type.Name, (Guid)jstr); } else if (type == typeof(char)) { Log.Info("{0} Value:{1}", type.Name, (char)jstr); } else if (type == typeof(Uri)) { Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri); } else { Log.Info("{0} Value:{1}", type.Name, (string)jstr); } if (jo.ToString() == jstr.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Object) { JsonObject jobj = new JsonObject((JsonObject)jo); if (jo.ToString() == jobj.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Number) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Boolean) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, (bool)jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } if (!result) { Assert.Fail("Test Failed!"); } }
public static bool Compare(JsonValue initValue, JsonValue newValue) { if (initValue == null && newValue == null) { return true; } if (initValue == null || newValue == null) { return false; } if (initValue is JsonPrimitive) { string initStr; if (initValue.JsonType == JsonType.String) { initStr = initValue.ToString(); } else { initStr = string.Format("\"{0}\"", ((JsonPrimitive)initValue).Value.ToString()); } string newStr; if (newValue is JsonPrimitive) { newStr = newValue.ToString(); initStr = HttpUtility.UrlDecode(HttpUtility.UrlEncode(initStr)); return initStr.Equals(newStr); } else if (newValue is JsonObject && newValue.Count == 1) { initStr = string.Format("{0}", initValue.ToString()); return ((JsonObject)newValue).Keys.Contains(initStr); } return false; } if (initValue.Count != newValue.Count) { return false; } if (initValue is JsonObject && newValue is JsonObject) { foreach (KeyValuePair<string, JsonValue> item in initValue) { if (!Compare(item.Value, newValue[item.Key])) { return false; } } return true; } if (initValue is JsonArray && newValue is JsonArray) { for (int i = 0; i < initValue.Count; i++) { if (!Compare(initValue[i], newValue[i])) { return false; } } return true; } return false; }
async public Task<JsonValue> PutAsync(string Path, JsonValue Data) { return await SendAsync(Path, "PUT", Data.ToString()); }
public void ToStringTest() { JsonObject target = new JsonObject(); JsonValue item1 = AnyInstance.AnyJsonValue1 ?? "not null"; JsonValue item2 = null; JsonValue item3 = AnyInstance.AnyJsonValue2 ?? "not null"; JsonValue item4 = AnyInstance.AnyJsonValue3 ?? "not null"; target.Add("item1", item1); target.Add("item2", item2); target.Add("item3", item3); target.Add("", item4); string expected = String.Format(CultureInfo.InvariantCulture, "{{\"item1\":{0},\"item2\":null,\"item3\":{1},\"\":{2}}}", item1.ToString(), item3.ToString(), item4.ToString()); Assert.Equal <string>(expected, target.ToString()); string json = "{\r\n \"item1\": \"hello\",\r\n \"item2\": null,\r\n \"item3\": [\r\n 1,\r\n 2,\r\n 3\r\n ],\r\n \"\": \"notnull\"\r\n}"; target = JsonValue.Parse(json) as JsonObject; Assert.Equal <string>(json.Replace("\r\n", "").Replace(" ", ""), target.ToString()); }
public static List<Cart> DeserializeArray(JsonValue json) { String data = json.ToString (); return (List<Cart>)JsonConvert.DeserializeObject(data, typeof(List<Cart>)); }
public async Task <UpdatePushTokenResponse> SendPushToServer(string token) { UpdatePushTokenResponse updateDeviceTokenResponse = new UpdatePushTokenResponse(); if (!String.IsNullOrEmpty(SessionHelper.AccessToken)) { UpdatePushTokenRequest updateDeviceTokenRequest = new UpdatePushTokenRequest(); updateDeviceTokenRequest.DevicePushToken = token; updateDeviceTokenRequest.DeviceType = Device.RuntimePlatform; updateDeviceTokenRequest.AuthToken = SessionHelper.AccessToken; System.Json.JsonValue updateUserResponse = await HttpRequestHelper <UpdatePushTokenRequest> .POSTreq(ServiceTypes.UpdatePushToken, updateDeviceTokenRequest); updateDeviceTokenResponse = JsonConvert.DeserializeObject <UpdatePushTokenResponse>(updateUserResponse.ToString()); } return(updateDeviceTokenResponse); }