IEnumerable<ClassDefiniation> VisitJsonValue(string propertyName, JsonValue jvalue, StringBuilder sb, string classHeader) { if (jvalue == null) { DefineProperty(propertyName, sb, "object"); return Enumerable.Empty<ClassDefiniation>(); } switch (jvalue.JsonType) { case JsonType.Array: return VisitArray(propertyName, jvalue, sb, classHeader); case JsonType.Object: return VisitObject(propertyName, jvalue, sb, classHeader); default: return VisitDefault(propertyName, jvalue, sb); } }
/// <constructor /> public ViewResultRow(JsonValue key, JsonValue value, string documentId, Document document) { Key = key; Value = value; DocumentId = documentId; Document = document; }
public static int ToInt (JsonValue jsonValue, string key, int defaultValue = 0) { int returnValue = JsonUtil.ContainsKey (jsonValue, key) ? jsonValue [key] as JsonPrimitive : defaultValue; return returnValue; }
public static double ToDouble (JsonValue jsonValue, string key, double defaultValue = 0.0) { double returnValue = JsonUtil.ContainsKey (jsonValue, key) ? jsonValue [key] as JsonPrimitive : defaultValue; return returnValue; }
private string displayString(JsonValue input) { string s = input.ToString (); int l = s.Length-2; string output = s.Substring(1, l); return output; }
public static string ToString (JsonValue jsonValue, string key, string defaultValue = "") { string returnValue = JsonUtil.ContainsKey (jsonValue, key) ? jsonValue [key] as JsonPrimitive : defaultValue; return returnValue; }
internal Parser(JsonValue json) { _sourceparser = json; MissingTokens = json.ContainsKey("missing_tokens") ? new HashSet<string>(json["missing_tokens"].Select(x => (string) x)) : new HashSet<string>(); }
private static List<LocationMatchDto> MakeLocationMatchDto(JsonValue returnString) { var returnStringResults = returnString["result"]; var restaurantMatches = new List<LocationMatchDto>(); if (returnStringResults["total"] != 0) { var returnStringRecords = returnStringResults["records"]; foreach (JsonValue establishment in returnStringRecords) { var foundLocation = new LocationMatchDto() { Name = establishment["PremiseName"], StreetNumber = establishment["PermiseStreetNo"], StreetName = establishment["PremiseStreet"], EstablishmentId = establishment["EstablishmentID"], Latitude = establishment["latitude"], Longitude = establishment["longitude"] }; restaurantMatches.Add(foundLocation); } } return restaurantMatches; }
public UserMention(JsonValue json) { Id = json["id"]; Name = json["name"]; ScreenName = json["screen_name"]; Indices = ((JsonArray)json["indices"]).Select(x => (int)x).ToArray(); }
public Student(JsonValue result) { int id; int.TryParse(result["studentID"], out id); StudentID = id; if (result ["dob"] != null) { Dob = DateTime.Parse (result ["dob"]); } Gender = checkGender (result ["gender"]); Degree = checkDegree (result ["degree"]); Status = checkStatus (result ["status"]); First_language = result ["first_language"]; Country = result ["country_origin"]; HSC = (result ["HSC"] != null); HscMark = result ["HSC_mark"]; IELTS = (result ["IELTS"] != null); IeltsMark = result ["IELTS_mark"]; TOEFL = (result ["TOEFL"] != null); ToeflMark = result ["TOEFL_mark"]; TAFE = (result ["TAFE"] != null); TafeMark = result ["TAFE_mark"]; CULT = (result ["CULT"] != null); CultMark = result ["CULT_mark"]; DEEP = (result ["InsearchDEEP"] != null); DeepMark = result ["InsearchDEEP_mark"]; Diploma = (result ["InsearchDiploma"] != null); DiplomaMark = result ["InsearchDiploma_mark"]; Foundation = (result ["foundationcourse"] != null); FoundationMark = result ["foundationcourse_mark"]; Alternative_contact = result ["alternative_contact"]; Prefered_name = result ["preferred_name"]; }
public string ConvertIntoCLRType(string keyName, string typeName, string toStringFormat, JsonValue input) { switch (typeName.ToLowerInvariant()) { case "datetime": DateTime dt = (DateTime)input[keyName]; return dt.ToString(toStringFormat, CultureInfo.InvariantCulture); case "int": return ((int)input[keyName]).ToString(CultureInfo.InvariantCulture); case "short": return ((short)input[keyName]).ToString(CultureInfo.InvariantCulture); case "long": return ((long)input[keyName]).ToString(CultureInfo.InvariantCulture); case "sbyte": return ((sbyte)input[keyName]).ToString(CultureInfo.InvariantCulture); case "byte": return ((byte)input[keyName]).ToString(CultureInfo.InvariantCulture); case "ushort": return ((ushort)input[keyName]).ToString(CultureInfo.InvariantCulture); case "uint": return ((uint)input[keyName]).ToString(CultureInfo.InvariantCulture); case "ulong": return ((ulong)input[keyName]).ToString(CultureInfo.InvariantCulture); case "decimal": return ((decimal)input[keyName]).ToString(CultureInfo.InvariantCulture); case "double": return ((double)input[keyName]).ToString("R", CultureInfo.InvariantCulture); case "float": return ((float)input[keyName]).ToString("R", CultureInfo.InvariantCulture); default: return "Type " + typeName + " not implemented yet; this will fail the client assertion."; } }
public static string GetString(JsonValue obj, string key) { if (obj.ContainsKey(key)) if (obj[key].JsonType == JsonType.String) return (string)obj[key]; return null; }
public static void ParseFriendInfo(Friend buddy, JsonValue item) { //buddy.Status = QQHelper.ParseOnlineStatus(item["stat"]).ToString(); buddy.NickName = item["nick"].ToString().Trim('\"'); buddy.Country = item["country"].ToString(); buddy.PersonalElucidation = item["province"].ToString(); buddy.City = item["city"].ToString(); buddy.Sex = item["gender"].ToString(); buddy.Face = item["face"].ToString(); var birthday = item["birthday"]; int year = (int)birthday["year"]; int month = (int)birthday["month"]; int day = (int)birthday["day"]; buddy.Birthday = new DateTime(year, month, day).ToString(); buddy.Allow = item["allow"].ToString(); buddy.Blood = item["blood"].ToString(); buddy.ShengXiao = item["shengxiao"].ToString(); buddy.Constel = item["constel"].ToString(); buddy.TelePhone = item["phone"].ToString(); buddy.MPhone = item["mobile"].ToString(); buddy.Email = item["email"].ToString(); buddy.Occupation = item["occupation"].ToString(); buddy.College = item["college"].ToString(); buddy.HomeUrl = item["homepage"].ToString(); buddy.PersonalElucidation = item["personal"].ToString(); }
public RelationshipUser(JsonValue json) { Id = json["id"]; ScreenName = json["screen_name"]; IsFollowing = json["following"]; IsFollowedBy = json["followed_by"]; }
public static EditTournamentStateDialog Initalize(JsonValue _json, Activity _context) { var dialogFragment = new EditTournamentStateDialog(); dialogFragment.json = _json; dialogFragment.context = _context; return dialogFragment; }
public RateLimitStatus(JsonValue json) { var resources = json["resources"]; HelpConfiguration = new RateLimit(resources["help"]["/help/configuration"]); HelpPrivacy = new RateLimit(resources["help"]["/help/privacy"]); StatusesOembed = new RateLimit(resources["statuses"]["/statuses/oembed"]); }
public static RestaurantInspectionDto MakeRestaurantInspectionDto(JsonValue returnString) { var returnStringResults = returnString["result"]; var inspectionList = new List<RestaurantInspectionDto>(); var inspectionData = new RestaurantInspectionDto(); if (returnStringResults["total"] != 0) { var returnStringRecords = returnStringResults["records"]; foreach (JsonValue establishment in returnStringRecords) { var locationFound = new RestaurantInspectionDto() { EstablishmentId = establishment["EstablishmentId"], EstablishmentName = establishment["EstablishmentName"], Grade = establishment["Grade"], Score = establishment["Score"], InspectionDate = establishment["InspectionDate"] }; inspectionList.Add(locationFound); } inspectionData = inspectionList.OrderByDescending(i => i.InspectionDate).ToList().FirstOrDefault(); } return inspectionData; }
public static List<YelpListingDto> MakeYelpListingDto(JsonValue restaurantList) { var yelpListingDtoList = new List<YelpListingDto>(); var businesses = restaurantList["businesses"]; foreach (JsonValue business in businesses) { var location = business["location"]; var address = location["address"]; var coordinates = location["coordinate"]; var listing = new YelpListingDto() { Id = business["id"], Name = business["name"], Address = address[0], City = location["city"], Latitude = coordinates["latitude"], Longitude = coordinates["longitude"], LocationClosed = business["is_closed"], MobileUrl = business["mobile_url"], Rating = business["rating"], NumberReviews = business["review_count"], RatingImage = business["rating_img_url_large"] }; yelpListingDtoList.Add(listing); } return yelpListingDtoList; }
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 void GenerateUpcomingMeals(string inURL, string inMethod) { lock (thisLock) { // Create an HTTP web request using the URL: HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (inURL)); request.ContentType = "application/json"; request.Method = inMethod; // Send the request to the server and wait for the response: using (WebResponse response = request.GetResponse ()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream ()) { // Use this stream to build a JSON document object: this.jsonDoc = JsonObject.Load (stream); } } int tempNum = this.mObject.NumElements; for (int i = this.mObject.NumElements - 1; i > -1; i--) { this.mObject.Remove (i); this.mAdapter.NotifyItemRemoved (i); } for (int k = 0; k < this.jsonDoc.Count; k++) { string[] separation = this.jsonDoc [k].ToString ().Split (';'); string finalSep0 = separation[0].Remove(0, 1); string finalSep2 = separation[2].Remove((separation[2].Length - 1)); Tuple<string, string, string> newTuple = new Tuple<string, string, string> (finalSep0, separation [1], finalSep2); this.mObject.Add (newTuple); this.mAdapter.NotifyItemInserted (k); } } }
public Torrent(JsonValue json) { if (json.Count == 1) { ID = json[0]; return; } int index = 0; ID = json[index++]; Status = (TorrentStatus)(int)json[index++]; Name = json[index++]; Size = json[index++]; PercentProgress = json[index++]; Downloaded = json[index++]; Uploaded = json[index++]; Ratio = json[index++]; UploadSpeed = json[index++]; DownloadSpeed = json[index++]; Eta = json[index++]; Label = json[index++]; PeersConnected = json[index++]; PeersInSwarm = json[index++]; SeedsConnected = json[index++]; SeedsInSwarm = json[index++]; Availability = json[index++]; QueueOrder = json[index++]; Remaining = json[index++]; }
public ClassDefiniation(string propertyName, JsonValue jValue, StringBuilder sb, string classHeadser) { PropertyName = propertyName; JValue = jValue; StringBuilder = sb; ClassHeader = classHeadser; }
/*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; }
public FullQuestion(JsonValue jsonValue, Spin spin) { this.Spin = spin; if (jsonValue.ContainsKey("powerup_question")) this.PowerupQuestion = new Question(jsonValue["powerup_question"], this); this.Question = new Question(jsonValue["question"], this); }
public Speaker (JsonValue json) : this() { Id = json["id"]; Name = json["name"]; TwitterHandle = json["twitterHandle"]; Bio = json["bio"]; HeadshotUrl = json["headshotUrl"]; }
public static NewTournamentDialog Initalize(Activity _context, JsonValue _json, bool _chkSignup) { var dialogFragment = new NewTournamentDialog (); dialogFragment.context = _context; dialogFragment.json = _json; dialogFragment.chkSignup = _chkSignup; return dialogFragment; }
public VBTeamrole(JsonValue json) { DB_Communicator db = DB_Communicator.getInstance(); this.teamId = db.convertAndInitializeToInt(db.containsKey(json, "teamId", DB_Communicator.JSON_TYPE_INT)); setUserType(db.convertAndInitializeToString(db.containsKey(json, "userType", DB_Communicator.JSON_TYPE_STRING))); this.role = db.convertAndInitializeToString(db.containsKey(json, "role", DB_Communicator.JSON_TYPE_STRING)); this.number = db.convertAndInitializeToInt(db.containsKey(json, "number", DB_Communicator.JSON_TYPE_INT)); this.position = db.convertAndInitializeToString(db.containsKey(json, "position", DB_Communicator.JSON_TYPE_STRING)); }
public JsonValue Post(JsonValue jsonContact) { dynamic contact = jsonContact; dynamic contactResponse = new JsonObject(); contactResponse.Name = contact.Name; contactResponse.ContactId = nextId++; return contactResponse; }
private static bool ContainsKey (JsonValue jsonValue, string key) { if (!jsonValue.ContainsKey (key)) { LogContext.Current.Log<JsonUtil> ("JsonValueString: Missing key", key); return false; } else return true; }
public static DataTable ConvertJSON2DataTable(string jsonString) { try { System.Json.JsonValue _retObj = System.Json.JsonValue.Load(new StringReader(jsonString)); System.Json.JsonValue _retCols = _retObj[0][0]["SimpDataArry"][2]; System.Json.JsonValue _retRows = _retObj[0][0]["SimpDataArry"][3]; DataTable _dt = new DataTable(); if (_retCols.JsonType == System.Json.JsonType.Array) { for (int _i = 0, _iCnt = _retCols.Count; _i < _iCnt; _i++) { System.Json.JsonValue _col = _retCols[_i]; if (_col.Count > 1) { string _colName = string.Format("{0}", _col[0]).Replace("\"", "");; string _colTypeVal = string.Format("{0}", _col[1]); int _colVal; if (int.TryParse(_colTypeVal, out _colVal)) { _dt.Columns.Add(_colName, ConvertColumnType(_colVal)); } } } } if (_retRows.JsonType == System.Json.JsonType.Array) { for (int _i = 0, _iCnt = _retRows.Count; _i < _iCnt; _i++) { System.Json.JsonValue _row = _retRows[_i]; object[] _objAry = CovertToObjectArray(_row); if (null != _objAry) { _dt.LoadDataRow(_objAry, false); } } } if (null != _dt) { return(_dt); } return(new DataTable()); } catch { return(new DataTable()); } }
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); }
public static IJsonValue AsValue(this System.Json.JsonValue self) { if (self == null) { return(JsonExtensions.Null()); } switch (self.JsonType) { case JsonType.Array: return(new JsonArray((System.Json.JsonArray)self)); case JsonType.Object: return(new JsonObject((System.Json.JsonObject)self)); default: return(new JsonValue(self)); } }
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 void refreshOpenweathermap() { string town = string.Empty; string temp = string.Empty; string osadki = string.Empty; string pressure = string.Empty; string cloudness = string.Empty; if (chechboxischecked == "false") { if (city == "sankt-peterburg") { string lat = "59.93"; string lon = "30.29"; // json var Gentral = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/find?lat=" + lat + "&lon=" + lon + "&APPID=c5ba134efa510143f5193f7d8e1f5bc7&units=metric"); // Город //var GentralTestCity = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/weather?lat=35&lon=139&APPID=c5ba134efa510143f5193f7d8e1f5bc7"); //System.Json.JsonValue ParsGentraltest = JsonValue.Parse(GentralTestCity); System.Json.JsonValue ParsGentral = JsonValue.Parse(Gentral); var CityName = ParsGentral.ValueOrDefault("city"); System.Json.JsonValue cityPars = JsonValue.Parse(CityName.ToString()); var NameValue = CityName["name"]; if (NameValue.ToString() == "\"Novaya Gollandiya\"") { town = "Погода в Санкт-Петербурге"; } // Температура System.Json.JsonValue ParsGentralTemp = JsonValue.Parse(Gentral); var List0 = ParsGentralTemp.ValueOrDefault("list"); var List1 = List0[0]; System.Json.JsonValue tempPars = JsonValue.Parse(List1.ToString()); var TempValue1 = tempPars["main"]; System.Json.JsonValue tempPars2 = JsonValue.Parse(TempValue1.ToString()); var TempValue2 = tempPars2["temp"]; temp = "+" + TempValue2.ToString(); // Оссадки System.Json.JsonValue ParsGentralOsadki = JsonValue.Parse(Gentral); var ListOsadki0 = ParsGentralOsadki.ValueOrDefault("list"); var ListOsadki1 = ListOsadki0[0]; System.Json.JsonValue OsadkiPars = JsonValue.Parse(ListOsadki1.ToString()); string OsadkiValue1 = OsadkiPars["weather"].ToString(); string osadkiTemp2 = new Regex(@"""description"":""(?<osadkiTemp2>[^<]+)"",").Match(OsadkiValue1).Groups["osadkiTemp2"].Value; // на будущее наклонную черту в регексе \ менять на " osadki = osadkiTemp2; // Давление System.Json.JsonValue ParsGentralPressure = JsonValue.Parse(Gentral); var ListPressure0 = ParsGentralPressure.ValueOrDefault("list"); var ListPressure1 = ListPressure0[0]; System.Json.JsonValue PressurePars = JsonValue.Parse(ListPressure1.ToString()); var PressureValue1 = PressurePars["main"]; System.Json.JsonValue PressurePars2 = JsonValue.Parse(PressureValue1.ToString()); var PressureValue2 = PressurePars2["pressure"]; pressure = Math.Round(Double.Parse(Convert.ToString(PressureValue2).Replace('.', ',')) * 0.75006375541921, 0).ToString() + " мм. рт. ст."; // Облачность System.Json.JsonValue ParsGentralOsadky = JsonValue.Parse(Gentral); var List00 = ParsGentralOsadky.ValueOrDefault("list"); var List11 = List00[0]; System.Json.JsonValue cloudnessPars = JsonValue.Parse(List11.ToString()); var CloudnessValue1 = cloudnessPars["clouds"]; System.Json.JsonValue cloudnessPars2 = JsonValue.Parse(CloudnessValue1.ToString()); var cloudnessPars3 = cloudnessPars2["all"]; cloudness = cloudnessPars3.ToString(); } else { if (city == "moskva") { string lat = "55.75"; string lon = "37.62"; // json var Gentral = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/find?lat=" + lat + "&lon=" + lon + "&APPID=c5ba134efa510143f5193f7d8e1f5bc7&units=metric"); // Город //var GentralTestCity = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/weather?lat=35&lon=139&APPID=c5ba134efa510143f5193f7d8e1f5bc7"); //System.Json.JsonValue ParsGentraltest = JsonValue.Parse(GentralTestCity); System.Json.JsonValue ParsGentral = JsonValue.Parse(Gentral); var CityName = ParsGentral.ValueOrDefault("city"); System.Json.JsonValue cityPars = JsonValue.Parse(CityName.ToString()); var NameValue = CityName["name"]; if (NameValue.ToString() == "\"Moscow\"") { town = "Погода в Москве"; } // Температура System.Json.JsonValue ParsGentralTemp = JsonValue.Parse(Gentral); var List0 = ParsGentralTemp.ValueOrDefault("list"); var List1 = List0[0]; System.Json.JsonValue tempPars = JsonValue.Parse(List1.ToString()); var TempValue1 = tempPars["main"]; System.Json.JsonValue tempPars2 = JsonValue.Parse(TempValue1.ToString()); var TempValue2 = tempPars2["temp"]; temp = "+" + TempValue2.ToString(); // Оссадки System.Json.JsonValue ParsGentralOsadki = JsonValue.Parse(Gentral); var ListOsadki0 = ParsGentralOsadki.ValueOrDefault("list"); var ListOsadki1 = ListOsadki0[0]; System.Json.JsonValue OsadkiPars = JsonValue.Parse(ListOsadki1.ToString()); string OsadkiValue1 = OsadkiPars["weather"].ToString(); string osadkiTemp2 = new Regex(@"""description"":""(?<osadkiTemp2>[^<]+)"",").Match(OsadkiValue1).Groups["osadkiTemp2"].Value; // на будущее наклонную черту в регексе \ менять на " osadki = osadkiTemp2; // Давление System.Json.JsonValue ParsGentralPressure = JsonValue.Parse(Gentral); var ListPressure0 = ParsGentralPressure.ValueOrDefault("list"); var ListPressure1 = ListPressure0[0]; System.Json.JsonValue PressurePars = JsonValue.Parse(ListPressure1.ToString()); var PressureValue1 = PressurePars["main"]; System.Json.JsonValue PressurePars2 = JsonValue.Parse(PressureValue1.ToString()); var PressureValue2 = PressurePars2["pressure"]; pressure = Math.Round(Double.Parse(Convert.ToString(PressureValue2).Replace('.', ',')) * 0.75006375541921, 0).ToString() + " мм. рт. ст."; // Облачность System.Json.JsonValue ParsGentralOsadky = JsonValue.Parse(Gentral); var List00 = ParsGentralOsadky.ValueOrDefault("list"); var List11 = List00[0]; System.Json.JsonValue cloudnessPars = JsonValue.Parse(List11.ToString()); var CloudnessValue1 = cloudnessPars["clouds"]; System.Json.JsonValue cloudnessPars2 = JsonValue.Parse(CloudnessValue1.ToString()); var cloudnessPars3 = cloudnessPars2["all"]; cloudness = cloudnessPars3.ToString(); } else { if (city == "kiev") { string lat = "50.45"; string lon = "30.5"; // json var Gentral = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/find?lat=" + lat + "&lon=" + lon + "&APPID=c5ba134efa510143f5193f7d8e1f5bc7&units=metric"); // Город //var GentralTestCity = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/weather?lat=35&lon=139&APPID=c5ba134efa510143f5193f7d8e1f5bc7"); //System.Json.JsonValue ParsGentraltest = JsonValue.Parse(GentralTestCity); System.Json.JsonValue ParsGentral = JsonValue.Parse(Gentral); var CityName = ParsGentral.ValueOrDefault("city"); System.Json.JsonValue cityPars = JsonValue.Parse(CityName.ToString()); var NameValue = CityName["name"]; string sdf = NameValue.ToString(); if (NameValue.ToString() == "\"Pushcha-Voditsa\"") { town = "Погода в Киеве"; } // Температура System.Json.JsonValue ParsGentralTemp = JsonValue.Parse(Gentral); var List0 = ParsGentralTemp.ValueOrDefault("list"); var List1 = List0[0]; System.Json.JsonValue tempPars = JsonValue.Parse(List1.ToString()); var TempValue1 = tempPars["main"]; System.Json.JsonValue tempPars2 = JsonValue.Parse(TempValue1.ToString()); var TempValue2 = tempPars2["temp"]; temp = "+" + TempValue2.ToString(); // Оссадки System.Json.JsonValue ParsGentralOsadki = JsonValue.Parse(Gentral); var ListOsadki0 = ParsGentralOsadki.ValueOrDefault("list"); var ListOsadki1 = ListOsadki0[0]; System.Json.JsonValue OsadkiPars = JsonValue.Parse(ListOsadki1.ToString()); string OsadkiValue1 = OsadkiPars["weather"].ToString(); string osadkiTemp2 = new Regex(@"""description"":""(?<osadkiTemp2>[^<]+)"",").Match(OsadkiValue1).Groups["osadkiTemp2"].Value; // на будущее наклонную черту в регексе \ менять на " osadki = osadkiTemp2; // Давление System.Json.JsonValue ParsGentralPressure = JsonValue.Parse(Gentral); var ListPressure0 = ParsGentralPressure.ValueOrDefault("list"); var ListPressure1 = ListPressure0[0]; System.Json.JsonValue PressurePars = JsonValue.Parse(ListPressure1.ToString()); var PressureValue1 = PressurePars["main"]; System.Json.JsonValue PressurePars2 = JsonValue.Parse(PressureValue1.ToString()); var PressureValue2 = PressurePars2["pressure"]; pressure = Math.Round(Double.Parse(Convert.ToString(PressureValue2).Replace('.', ',')) * 0.75006375541921, 0).ToString() + " мм. рт. ст."; // Облачность System.Json.JsonValue ParsGentralOsadky = JsonValue.Parse(Gentral); var List00 = ParsGentralOsadky.ValueOrDefault("list"); var List11 = List00[0]; System.Json.JsonValue cloudnessPars = JsonValue.Parse(List11.ToString()); var CloudnessValue1 = cloudnessPars["clouds"]; System.Json.JsonValue cloudnessPars2 = JsonValue.Parse(CloudnessValue1.ToString()); var cloudnessPars3 = cloudnessPars2["all"]; cloudness = cloudnessPars3.ToString(); } } } } else { if (chechboxischecked == "true") { string lat = latGeneral; string lon = lonGeneral; // json var Gentral = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/find?lat=" + lat + "&lon=" + lon + "&APPID=c5ba134efa510143f5193f7d8e1f5bc7&units=metric"); // Город //var GentralTestCity = new System.Net.WebClient().DownloadString("http://api.openweathermap.org/data/2.5/forecast/weather?lat=35&lon=139&APPID=c5ba134efa510143f5193f7d8e1f5bc7"); //System.Json.JsonValue ParsGentraltest = JsonValue.Parse(GentralTestCity); System.Json.JsonValue ParsGentral = JsonValue.Parse(Gentral); var CityName = ParsGentral.ValueOrDefault("city"); System.Json.JsonValue cityPars = JsonValue.Parse(CityName.ToString()); var NameValue = CityName["name"]; town = "Погода в " + NameValue.ToString(); // Температура System.Json.JsonValue ParsGentralTemp = JsonValue.Parse(Gentral); var List0 = ParsGentralTemp.ValueOrDefault("list"); var List1 = List0[0]; System.Json.JsonValue tempPars = JsonValue.Parse(List1.ToString()); var TempValue1 = tempPars["main"]; System.Json.JsonValue tempPars2 = JsonValue.Parse(TempValue1.ToString()); var TempValue2 = tempPars2["temp"]; temp = "+" + TempValue2.ToString(); // Оссадки System.Json.JsonValue ParsGentralOsadki = JsonValue.Parse(Gentral); var ListOsadki0 = ParsGentralOsadki.ValueOrDefault("list"); var ListOsadki1 = ListOsadki0[0]; System.Json.JsonValue OsadkiPars = JsonValue.Parse(ListOsadki1.ToString()); string OsadkiValue1 = OsadkiPars["weather"].ToString(); string osadkiTemp2 = new Regex(@"""description"":""(?<osadkiTemp2>[^<]+)"",").Match(OsadkiValue1).Groups["osadkiTemp2"].Value; // на будущее наклонную черту в регексе \ менять на " osadki = osadkiTemp2; // Давление System.Json.JsonValue ParsGentralPressure = JsonValue.Parse(Gentral); var ListPressure0 = ParsGentralPressure.ValueOrDefault("list"); var ListPressure1 = ListPressure0[0]; System.Json.JsonValue PressurePars = JsonValue.Parse(ListPressure1.ToString()); var PressureValue1 = PressurePars["main"]; System.Json.JsonValue PressurePars2 = JsonValue.Parse(PressureValue1.ToString()); var PressureValue2 = PressurePars2["pressure"]; pressure = Math.Round(Double.Parse(Convert.ToString(PressureValue2).Replace('.', ',')) * 0.75006375541921, 0).ToString() + " мм. рт. ст."; // Облачность System.Json.JsonValue ParsGentralOsadky = JsonValue.Parse(Gentral); var List00 = ParsGentralOsadky.ValueOrDefault("list"); var List11 = List00[0]; System.Json.JsonValue cloudnessPars = JsonValue.Parse(List11.ToString()); var CloudnessValue1 = cloudnessPars["clouds"]; System.Json.JsonValue cloudnessPars2 = JsonValue.Parse(CloudnessValue1.ToString()); var cloudnessPars3 = cloudnessPars2["all"]; cloudness = cloudnessPars3.ToString(); } } TBCityResult.Text = town; TBtempResult.Text = temp; TBCloudnessResult.Text = cloudness; TBCloudsResult.Text = osadki; TBPressureResult.Text = pressure; InterFase(); }
/// <summary> /// Performs the binding of the dynamic binary operation. /// </summary> /// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { if (binder == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("binder")); } if (arg == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("arg")); } Expression thisExpression = this.Expression; Expression otherExpression = arg.Expression; Expression operExpression = null; JsonValue otherValue = arg.Value as JsonValue; JsonValue thisValue = this.Value as JsonValue; OperationSupport supportValue = JsonValueDynamicMetaObject.GetBinaryOperationSupport(binder.Operation, thisValue, arg.Value); if (supportValue == OperationSupport.Supported) { if (otherValue != null) { if (thisValue is JsonPrimitive && otherValue is JsonPrimitive) { //// operation on primitive types. JsonValueDynamicMetaObject.GetBinaryOperandExpressions(binder.Operation, this, arg, ref thisExpression, ref otherExpression); } else { //// operation on JsonValue types. thisExpression = Expression.Convert(thisExpression, typeof(JsonValue)); otherExpression = Expression.Convert(otherExpression, typeof(JsonValue)); } } else { if (arg.Value != null) { //// operation on JSON primitive and CLR primitive JsonValueDynamicMetaObject.GetBinaryOperandExpressions(binder.Operation, this, arg, ref thisExpression, ref otherExpression); } else { //// operation on JsonValue and null. thisExpression = Expression.Convert(thisExpression, typeof(JsonValue)); if (thisValue.JsonType == JsonType.Default) { thisExpression = Expression.Constant(null); } } } operExpression = JsonValueDynamicMetaObject.GetBinaryOperationExpression(binder.Operation, thisExpression, otherExpression); } if (operExpression == null) { operExpression = JsonValueDynamicMetaObject.GetOperationErrorExpression(supportValue, binder.Operation, thisValue, arg.Value); } operExpression = Expression.Convert(operExpression, typeof(object)); return(new DynamicMetaObject(operExpression, this.DefaultRestrictions)); }
/// <summary> /// Class constructor. /// </summary> /// <param name="parameter">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param> internal JsonValueDynamicMetaObject(Expression parameter, JsonValue value) : base(parameter, BindingRestrictions.Empty, value) { }
/// <summary> /// Gets the operation support value for the specified operation on the specified operand. /// </summary> /// <param name="operation">The operation type.</param> /// <param name="thisValue">The JsonValue instance to check operation for.</param> /// <returns>An <see cref="OperationSupport"/> value.</returns> private static OperationSupport GetUnaryOperationSupport(ExpressionType operation, JsonValue thisValue) { //// Unary operators: +, -, !, ~, false (&&), true (||) //// unsupported: ++, -- switch (operation) { case ExpressionType.UnaryPlus: case ExpressionType.Negate: case ExpressionType.OnesComplement: case ExpressionType.IsFalse: case ExpressionType.IsTrue: break; case ExpressionType.Not: //// The DLR converts the 'Not' operation into a 'OnesComplement' operation for integer numbers, need to block that scenario. bool boolVal; if (!thisValue.TryReadAs <bool>(out boolVal)) { return(OperationSupport.NotSupportedOnOperand); } break; default: return(OperationSupport.NotSupported); } return(OperationSupport.Supported); }
/// <summary> /// Gets the operation support value for the specified operation and operands. /// </summary> /// <param name="operation">The operation type.</param> /// <param name="thisValue">The JsonValue instance to check operation for.</param> /// <param name="operand">The second operand instance.</param> /// <returns>An <see cref="OperationSupport"/> value.</returns> private static OperationSupport GetBinaryOperationSupport(ExpressionType operation, JsonValue thisValue, object operand) { //// Supported binary operators: +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, <= bool isCompareOperation = false; JsonValue otherValue = operand as JsonValue; switch (operation) { //// supported binary operations case ExpressionType.Add: case ExpressionType.Subtract: case ExpressionType.Multiply: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.Or: case ExpressionType.ExclusiveOr: case ExpressionType.LeftShift: case ExpressionType.RightShift: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: break; //// compare operations: case ExpressionType.Equal: case ExpressionType.NotEqual: isCompareOperation = true; break; default: return(OperationSupport.NotSupported); } if (operand != null) { bool thisIsPrimitive = thisValue is JsonPrimitive; if (otherValue != null) { if (!(otherValue is JsonPrimitive) || !thisIsPrimitive) { //// When either value is non-primitive it must be a compare operation. if (!isCompareOperation) { return(OperationSupport.NotSupportedOnJsonType); } } } else { //// if operand is not a JsonValue it must be a primitive CLR type and first operand must be a JsonPrimitive. if (!thisIsPrimitive) { return(OperationSupport.NotSupportedOnJsonType); } JsonPrimitive primitiveValue = null; if (!JsonPrimitive.TryCreate(operand, out primitiveValue)) { return(OperationSupport.NotSupportedOnValueType); } } } else { //// when operand is null only compare operations are valid. if (!isCompareOperation) { return(OperationSupport.NotSupportedOnOperand); } } return(OperationSupport.Supported); }
/// <summary> /// Returns an expression representing a 'throw' instruction based on the specified <see cref="OperationSupport"/> value. /// </summary> /// <param name="supportValue">The <see cref="OperationSupport"/> value.</param> /// <param name="operation">The operation type.</param> /// <param name="thisValue">The operation left operand.</param> /// <param name="operand">The operation right operand.</param> /// <returns>A <see cref="Expression"/> representing a 'throw' instruction.</returns> private static Expression GetOperationErrorExpression(OperationSupport supportValue, ExpressionType operation, JsonValue thisValue, object operand) { string exceptionMessage; string operandTypeName = operand != null?operand.GetType().FullName : "<null>"; switch (supportValue) { default: case OperationSupport.NotSupported: case OperationSupport.NotSupportedOnJsonType: case OperationSupport.NotSupportedOnValueType: exceptionMessage = SG.GetString(SR.OperatorNotDefinedForJsonType, operation, thisValue.JsonType); break; case OperationSupport.NotSupportedOnOperand: exceptionMessage = SG.GetString(SR.OperatorNotAllowedOnOperands, operation, thisValue.GetType().FullName, operandTypeName); break; } return(Expression.Throw(Expression.Constant(new InvalidOperationException(exceptionMessage)), typeof(object))); }
private bool TestPrimitiveType(string typeName) { bool retValue = true; bool specialCase = false; int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonPrimitive sourceJson = null; JsonPrimitive sourceJson2; object tempValue = null; switch (typeName.ToLower()) { case "boolean": tempValue = PrimitiveCreator.CreateInstanceOfBoolean(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString().ToLower()); sourceJson2 = new JsonPrimitive((bool)tempValue); break; case "byte": tempValue = PrimitiveCreator.CreateInstanceOfByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((byte)tempValue); break; case "char": sourceJson2 = new JsonPrimitive((char)PrimitiveCreator.CreateInstanceOfChar(rndGen)); specialCase = true; break; case "datetime": tempValue = PrimitiveCreator.CreateInstanceOfDateTime(rndGen); sourceJson2 = new JsonPrimitive((DateTime)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "decimal": tempValue = PrimitiveCreator.CreateInstanceOfDecimal(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(((decimal)tempValue).ToString(NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive((decimal)tempValue); break; case "double": double tempDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempDouble.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(tempDouble); break; case "guid": sourceJson2 = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfGuid(rndGen)); specialCase = true; break; case "int16": tempValue = PrimitiveCreator.CreateInstanceOfInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((short)tempValue); break; case "int32": tempValue = PrimitiveCreator.CreateInstanceOfInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((int)tempValue); break; case "int64": tempValue = PrimitiveCreator.CreateInstanceOfInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((long)tempValue); break; case "sbyte": tempValue = PrimitiveCreator.CreateInstanceOfSByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((sbyte)tempValue); break; case "single": float fltValue = PrimitiveCreator.CreateInstanceOfSingle(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(fltValue.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(fltValue); break; case "string": do { tempValue = PrimitiveCreator.CreateInstanceOfString(rndGen); } while (tempValue == null); sourceJson2 = new JsonPrimitive((string)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "uint16": tempValue = PrimitiveCreator.CreateInstanceOfUInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ushort)tempValue); break; case "uint32": tempValue = PrimitiveCreator.CreateInstanceOfUInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((uint)tempValue); break; case "uint64": tempValue = PrimitiveCreator.CreateInstanceOfUInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ulong)tempValue); break; case "uri": Uri uri = null; do { try { uri = PrimitiveCreator.CreateInstanceOfUri(rndGen); } catch (UriFormatException) { } } while (uri == null); sourceJson2 = new JsonPrimitive(uri); specialCase = true; break; case "null": sourceJson = (JsonPrimitive)JsonValue.Parse("null"); sourceJson2 = null; break; default: sourceJson = null; sourceJson2 = null; break; } if (!specialCase) { // comparison between two constructors if (!JsonValueVerifier.Compare(sourceJson, sourceJson2)) { Log.Info("(JsonPrimitive)JsonValue.Parse(string) failed to match the results from default JsonPrimitive(obj)constructor for type {0}", typeName); retValue = false; } if (sourceJson != null) { // test JsonValue.Load(TextReader) JsonPrimitive newJson = null; using (StringReader sr = new StringReader(sourceJson.ToString())) { newJson = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson = null; newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString()); if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } } else { // test JsonValue.Load(TextReader) JsonPrimitive newJson2 = null; using (StringReader sr = new StringReader(sourceJson2.ToString())) { newJson2 = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson2 = null; newJson2 = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } return(retValue); }
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); }
public void JsonArrayEventsTest() { int seed = 1; const int maxArrayLength = 1024; Random rand = new Random(seed); JsonArray ja = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, rand.Next(maxArrayLength)); int addPosition = ja.Count; JsonValue insertValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( ja, arr => arr.Add(insertValue), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, addPosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, addPosition)), }); addPosition = ja.Count; JsonValue jv1 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); JsonValue jv2 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( ja, arr => arr.AddRange(jv1, jv2), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs( jv1, JsonValueChange.Add, addPosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs( jv2, JsonValueChange.Add, addPosition + 1)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs( jv1, JsonValueChange.Add, addPosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs( jv2, JsonValueChange.Add, addPosition + 1)), }); int replacePosition = rand.Next(ja.Count - 1); JsonValue oldValue = ja[replacePosition]; JsonValue newValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( ja, arr => arr[replacePosition] = newValue, new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(newValue, JsonValueChange.Replace, replacePosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(oldValue, JsonValueChange.Replace, replacePosition)), }); int insertPosition = rand.Next(ja.Count - 1); insertValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( ja, arr => arr.Insert(insertPosition, insertValue), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, insertPosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, insertPosition)), }); TestEvents( ja, arr => arr.RemoveAt(insertPosition), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, insertPosition)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, insertPosition)), }); ja.Insert(0, insertValue); TestEvents( ja, arr => arr.Remove(insertValue), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, 0)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, 0)), }); TestEvents( ja, arr => arr.Clear(), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)), }); ja = new JsonArray(1, 2, 3); TestEvents( ja, arr => arr.Remove(new JsonPrimitive("Not there")), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> >()); JsonValue elementInArray = ja[1]; TestEvents( ja, arr => arr.Remove(elementInArray), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)), }); }
public void JsonObjectEventsTest() { int seed = 1; const int maxObj = 10; const string key1 = "first"; const string key2 = "second"; const string key3 = "third"; const string key4 = "fourth"; const string key5 = "fifth"; JsonObject jo = new JsonObject { { key1, SpecialJsonValueHelper.GetRandomJsonPrimitives(seed) }, { key2, SpecialJsonValueHelper.GetRandomJsonPrimitives(seed) }, { key3, null }, }; JsonObject objToAdd = SpecialJsonValueHelper.CreateRandomPopulatedJsonObject(seed, maxObj); TestEvents( jo, obj => obj.Add(key4, objToAdd), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(objToAdd, JsonValueChange.Add, key4)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(objToAdd, JsonValueChange.Add, key4)), }, obj => obj.Add("key44", objToAdd)); JsonArray jaToAdd = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, maxObj); JsonValue replaced = jo[key2]; TestEvents( jo, obj => obj[key2] = jaToAdd, new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jaToAdd, JsonValueChange.Replace, key2)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(replaced, JsonValueChange.Replace, key2)), }); JsonValue jpToAdd = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( jo, obj => obj[key5] = jpToAdd, new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jpToAdd, JsonValueChange.Add, key5)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jpToAdd, JsonValueChange.Add, key5)), }); jo.Remove(key4); jo.Remove(key5); JsonValue jp1 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); JsonValue jp2 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed); TestEvents( jo, obj => obj.AddRange(new JsonObject { { key4, jp1 }, { key5, jp1 } }), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp1, JsonValueChange.Add, key4)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Add, key5)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp1, JsonValueChange.Add, key4)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Add, key5)), }, obj => obj.AddRange(new JsonObject { { "new key", jp1 }, { "newnewKey", jp2 } })); TestEvents( jo, obj => obj.Remove(key5), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Remove, key5)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Remove, key5)), }); TestEvents( jo, obj => obj.Remove("not there"), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> >()); jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } }; TestEvents( jo, obj => obj.Clear(), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)), }); jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } }; TestEvents( jo, obj => ((IDictionary <string, JsonValue>)obj).Remove(new KeyValuePair <string, JsonValue>(key2, jo[key2])), new List <Tuple <bool, JsonValue, JsonValueChangeEventArgs> > { new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)), new Tuple <bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)), }, obj => ((IDictionary <string, JsonValue>)obj).Remove(new KeyValuePair <string, JsonValue>(key1, jo[key1]))); }
internal JsonValue(System.Json.JsonValue value) { this.value = value; }