/** * Makes four radar search requests for the given keyword, then parses the * json output and returns the search results as a collection of LatLng objects. * * @param keyword A string to use as a search term for the radar search * @return Returns the search results from radar search as a collection * of LatLng objects. */ private List <LatLng> getPoints(string keyword) { Dictionary <string, LatLng> results = new Dictionary <string, LatLng>(); // Calculate four equidistant points around Sydney to use as search centers // so that four searches can be done. List <LatLng> searchCenters = new List <LatLng>(4); for (int heading = 45; heading < 360; heading += 90) { searchCenters.Add(SphericalUtil.ComputeOffset(SYDNEY, SEARCH_RADIUS / 2, heading)); } for (int j = 0; j < 4; j++) { string jsonResults = getJsonPlaces(keyword, searchCenters[j]); try { // Create a JSON object hierarchy from the results JSONObject jsonObj = new JSONObject(jsonResults); JSONArray pointsJsonArray = jsonObj.GetJSONArray("results"); // Extract the Place descriptions from the results for (int i = 0; i < pointsJsonArray.Length(); i++) { if (!results.ContainsKey(pointsJsonArray.GetJSONObject(i).GetString("id"))) { JSONObject location = pointsJsonArray.GetJSONObject(i) .GetJSONObject("geometry").GetJSONObject("location"); results.Add(pointsJsonArray.GetJSONObject(i).GetString("id"), new LatLng(location.GetDouble("lat"), location.GetDouble("lng"))); } } } catch (JSONException) { Toast.MakeText(this, "Cannot process JSON results", ToastLength.Short).Show(); } } return(results.Values.ToList()); }
public List <string> Getinfo(string address, string type) { //address = "52.379189, 4.899431"; string importstring; //string type = "point_of_interest"; List <string> result = new List <string>(); string URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + "location=" + address + "" + "&radius=1500" + "&type=" + type + "" + "&key=AIzaSyB14uIG5whsFqi082hecZtzjPibj4r0KjU"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); importstring = reader.ReadToEnd(); JSONObject places = new JSONObject(importstring); JSONArray results = places.GetJSONArray("results"); string status = places.GetString("status"); int test = places.Length(); if (status == "OK") { if (places.Length() == 3) { JSONObject Name = results.GetJSONObject(0); result.Add(Name.GetString("name").ToString() + " || " + Name.GetString("vicinity").ToString()); } else { for (int i = 0; i < places.Length(); i++) { JSONObject Name = results.GetJSONObject(i); result.Add(Name.GetString("name").ToString() + " || " + Name.GetString("vicinity").ToString()); } } } } return(result); }
public static int GetCatalogId(string catname) { if (Catalog.IsNull(0)) { Catalog = new JSONArray(Get(ActionGetCatalog)); } try { for (int i = 0; i < Catalog.Length(); i++) { JSONObject Cate = Catalog.GetJSONObject(i); String name = Cate.GetString("cate_name"); if (name == catname) { return(Cate.GetInt("cate_id")); } } } finally { } return(0); }
public string[] GetSkeletonBoneNames() { JSONArray array = json.GetJSONObject("skeleton").GetJSONArray("bones"); int size = array.Length(); string[] result = new string[size]; for (int i = 0; i < size; ++i) { result[i] = array.GetJSONObject(i).GetString("name"); } return(result); }
private void readCountriesHierarchy(Dictionary <String, String> mapsItemsCodes, string currentContinentCode, JSONArray countriesArray) { for (int i = 0; i < countriesArray.Length(); i++) { try { JSONObject currentCountryObject = countriesArray.GetJSONObject(i); if (currentCountryObject != null) { try { String currentCountryCode = currentCountryObject.GetString(COUNTRY_CODE_ID); if ((currentContinentCode != null) && (currentCountryCode != null)) { mapsItemsCodes.Add(currentCountryCode, currentContinentCode); try { JSONArray citiesArray = currentCountryObject.GetJSONArray(CITY_CODES_ID); if (citiesArray != null) { readCitiesHierarchy(mapsItemsCodes, currentCountryCode, citiesArray); } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } try { JSONArray statesArray = currentCountryObject.GetJSONArray(STATE_CODES_ID); if (statesArray != null) { readStatesHierarchy(mapsItemsCodes, currentCountryCode, statesArray); } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } } }
public string[] GetGeometryNames() { JSONArray array = json.GetJSONArray("geometries"); int size = array.Length(); string[] result = new string[size]; for (int i = 0; i < size; ++i) { result[i] = array.GetJSONObject(i).GetString("name"); } return(result); }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> public virtual void TestNodesHelper(string path, string media) { WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); MockNM nm2 = rm.RegisterNode("h2:1235", 5121); rm.SendNodeStarted(nm1); rm.SendNodeStarted(nm2); rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running); rm.NMwaitForState(nm2.GetNodeId(), NodeState.Running); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path(path).Accept (media).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject nodes = json.GetJSONObject("nodes"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length() ); JSONArray nodeArray = nodes.GetJSONArray("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, nodeArray.Length ()); JSONObject info = nodeArray.GetJSONObject(0); string id = info.Get("id").ToString(); if (id.Matches("h1:1234")) { VerifyNodeInfo(info, nm1); VerifyNodeInfo(nodeArray.GetJSONObject(1), nm2); } else { VerifyNodeInfo(info, nm2); VerifyNodeInfo(nodeArray.GetJSONObject(1), nm1); } }
private PolylineOptions JSONRuta() { PolylineOptions lineOptions = new PolylineOptions(); try { JSONObject json = rutaEntreDosPuntos(getDirectionsUrl(currentLocation, new LatLng(lat, lng))); if (json != null) { JSONArray ruta = json.GetJSONArray("routes").GetJSONObject(0).GetJSONArray("legs").GetJSONObject(0).GetJSONArray("steps"); int numTramos = ruta.Length(); for (int i = 0; i < numTramos; i++) { JSONObject puntosCodificados = ruta.GetJSONObject(i).GetJSONObject("start_location"); lineOptions.Add(new LatLng(puntosCodificados.GetDouble("lat"), puntosCodificados.GetDouble("lng"))); puntosCodificados = ruta.GetJSONObject(i).GetJSONObject("polyline"); List <LatLng> arr = decodePoly(puntosCodificados.GetString("points")); foreach (LatLng pos in arr) { lineOptions.Add(pos); } puntosCodificados = ruta.GetJSONObject(i).GetJSONObject("end_location"); lineOptions.Add(new LatLng(puntosCodificados.GetDouble("lat"), puntosCodificados.GetDouble("lng"))); } } } catch (JSONException e) { throw e; } catch (Exception ex) { throw ex; } return(lineOptions); }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> public virtual void TestNodeHelper(string path, string media) { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; Dictionary <string, string> hash = AddAppContainers(app); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app2 = new MockApp(2); nmContext.GetApplications()[app2.GetAppId()] = app2; Dictionary <string, string> hash2 = AddAppContainers(app2); ClientResponse response = r.Path("ws").Path("v1").Path("node").Path(path).Accept( media).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject info = json.GetJSONObject("apps"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length()); JSONArray appInfo = info.GetJSONArray("app"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, appInfo.Length ()); string id = appInfo.GetJSONObject(0).GetString("id"); if (id.Matches(app.GetAppId().ToString())) { VerifyNodeAppInfo(appInfo.GetJSONObject(0), app, hash); VerifyNodeAppInfo(appInfo.GetJSONObject(1), app2, hash2); } else { VerifyNodeAppInfo(appInfo.GetJSONObject(0), app2, hash2); VerifyNodeAppInfo(appInfo.GetJSONObject(1), app, hash); } }
/// <summary> /// Gets the transit details. /// </summary> /// <returns>Transit details.</returns> public string[] GetTransitDetails() { List <string> transitSteps = new List <string>(); JSONObject geoData = new JSONObject(GetPublicTransportData()); // Check if the program found the location string status = geoData.GetString("status"); if (status.ToString() != "OK") { string[] error = new string[1]; error[0] = "No location was found"; return(error); } JSONArray routes = geoData.GetJSONArray("routes"); for (int i = 0; i < routes.Length(); i++) { JSONArray legs = routes.GetJSONObject(i).GetJSONArray("legs"); JSONArray steps = legs.GetJSONObject(0).GetJSONArray("steps"); for (int j = 0; j < steps.Length(); j++) { if (steps.GetJSONObject(j).GetString("travel_mode") == "TRANSIT") { JSONObject transitStep = steps.GetJSONObject(j); JSONObject transitDetails = transitStep.GetJSONObject("transit_details"); string arrivalTime = transitDetails.GetJSONObject("arrival_time").GetString("text"); string arrivalStop = transitDetails.GetJSONObject("arrival_stop").GetString("name"); string departureTime = transitDetails.GetJSONObject("departure_time").GetString("text"); string departureStop = transitDetails.GetJSONObject("departure_stop").GetString("name"); transitSteps.Add("Departure: " + departureTime + " - " + departureStop + "\n" + "Arrival: " + arrivalTime + " - " + arrivalStop + "\n"); } } } return(transitSteps.ToArray()); }
public void ReadQuizFromFile(View view) { ClearQuizStatus(); JSONObject jsonObject = JsonUtils.LoadJsonFile(this, QUIZ_JSON_FILE); JSONArray jsonArray = jsonObject.GetJSONArray(JsonUtils.JSON_FIELD_QUESTIONS); for (int i = 0; i < jsonArray.Length(); i++) { JSONObject questionObject = jsonArray.GetJSONObject(i); Question question = Question.FromJSon(questionObject, question_index++); AddQuestionDataItem(question); SetNewQuestionStatus(question.question); } }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> private void VerifySubQueue(JSONObject info, string q, float parentAbsCapacity, float parentAbsMaxCapacity) { int numExpectedElements = 13; bool isParentQueue = true; if (!info.Has("queues")) { numExpectedElements = 25; isParentQueue = false; } NUnit.Framework.Assert.AreEqual("incorrect number of elements", numExpectedElements , info.Length()); TestRMWebServicesCapacitySched.QueueInfo qi = isParentQueue ? new TestRMWebServicesCapacitySched.QueueInfo (this) : new TestRMWebServicesCapacitySched.LeafQueueInfo(this); qi.capacity = (float)info.GetDouble("capacity"); qi.usedCapacity = (float)info.GetDouble("usedCapacity"); qi.maxCapacity = (float)info.GetDouble("maxCapacity"); qi.absoluteCapacity = (float)info.GetDouble("absoluteCapacity"); qi.absoluteMaxCapacity = (float)info.GetDouble("absoluteMaxCapacity"); qi.absoluteUsedCapacity = (float)info.GetDouble("absoluteUsedCapacity"); qi.numApplications = info.GetInt("numApplications"); qi.queueName = info.GetString("queueName"); qi.state = info.GetString("state"); VerifySubQueueGeneric(q, qi, parentAbsCapacity, parentAbsMaxCapacity); if (isParentQueue) { JSONArray arr = info.GetJSONObject("queues").GetJSONArray("queue"); // test subqueues for (int i = 0; i < arr.Length(); i++) { JSONObject obj = arr.GetJSONObject(i); string q2 = q + "." + obj.GetString("queueName"); VerifySubQueue(obj, q2, qi.absoluteCapacity, qi.absoluteMaxCapacity); } } else { TestRMWebServicesCapacitySched.LeafQueueInfo lqi = (TestRMWebServicesCapacitySched.LeafQueueInfo )qi; lqi.numActiveApplications = info.GetInt("numActiveApplications"); lqi.numPendingApplications = info.GetInt("numPendingApplications"); lqi.numContainers = info.GetInt("numContainers"); lqi.maxApplications = info.GetInt("maxApplications"); lqi.maxApplicationsPerUser = info.GetInt("maxApplicationsPerUser"); lqi.userLimit = info.GetInt("userLimit"); lqi.userLimitFactor = (float)info.GetDouble("userLimitFactor"); VerifyLeafQueueGeneric(q, lqi); } }
//============================================================================================== // Utils //============================================================================================== private static IList <DemoParticipant> ParticipantsFromJson(JSONArray participantArray) { IList <DemoParticipant> participants = new List <DemoParticipant>(participantArray.Length()); for (int i = 0; i < participantArray.Length(); i++) { JSONObject participantObject = participantArray.GetJSONObject(i); DemoParticipant participant = new DemoParticipant(); participant.Id = participantObject.OptString("id"); participant.Name = participantObject.OptString("name"); participant.AvatarUrl = null; participants.Add(participant); } return(participants); }
// Datasets from http://data.gov.au private List <LatLng> readItems(int resource) { List <LatLng> list = new List <LatLng>(); Stream inputStream = Resources.OpenRawResource(resource); string json = new Scanner(inputStream).UseDelimiter("\\A").Next(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.Length(); i++) { JSONObject jsonObject = array.GetJSONObject(i); double lat = jsonObject.GetDouble("lat"); double lng = jsonObject.GetDouble("lng"); list.Add(new LatLng(lat, lng)); } return(list); }
/// <summary> /// 将返回的json数据解析成weather的实体类 /// </summary> /// <param name="respose"></param> /// <returns></returns> public static Weather HandleWeatherResponse(string respose) { if (string.IsNullOrEmpty(respose)) { try { var jsonObject = new JSONObject(respose); JSONArray jsonArray = jsonObject.GetJSONArray("HeWeather6"); var weatherContent = jsonArray.GetJSONObject(0).ToString(); } catch (JSONException e) { e.PrintStackTrace(); } } }
public void ProcessImageConnectServiceCompleted(string jsonString) { Dictionary <string, Object> resultDict = new Dictionary <string, Object>(); JSONObject jsonResponse = new JSONObject(jsonString); JSONArray fields = jsonResponse.GetJSONArray("Fields"); for (int i = 0; i < fields.Length(); i++) { JSONObject dict = fields.GetJSONObject(i); string key = dict.GetString("Key"); string value = dict.GetString("Value"); resultDict.Add(key, value); } App.ProcessingListener.finishedProcessing(resultDict); }
protected override void OnPostExecute(Java.Lang.Object result) { progressDialog.Dismiss(); if (result == null) { return; } string json = result.ToString(); //ShowDialog("Server Response",json); //Log.e("LOG", "progressDialog.dismiss();"); try { JSONObject jsonObject = new JSONObject(json); JSONArray jsonArray = jsonObject.GetJSONArray("server_response"); JSONObject jo = jsonArray.GetJSONObject(0); string code = jo.GetString("code"); string message = jo.GetString("message"); // Log.e("LOG", "code: " + code); //Log.e("LOG", "message: " + message); if (code.Equals("reg_true")) { ShowDialog("Registration Success", message, code); } else if (code.Equals("reg_false")) { ShowDialog("Registration Failed", message, code); } else if (code.Equals("login_true")) { Intent i = new Intent(activity, typeof(WelcomeUser)); i.PutExtra("message", message); activity.StartActivity(i); } else if (code.Equals("login_false")) { ShowDialog("Login Failed", message, code); } } catch (JSONException e) { // e.printStackTrace(); } }
public static IList <ListBids> ShowBidsByUserId() { IList <ListBids> listBids1 = new List <ListBids> (); try { var JSON = new JSONArray(Get(ActionListBid)); try { for (int i = 0; i < JSON.Length(); i++) { JSONObject Cate = JSON.GetJSONObject(i); String date = Cate.GetString("date_on"); var tempList = new ListBids(); tempList.ID = Cate.GetInt("bids_id"); tempList.CateID = Cate.GetInt("cate_id"); tempList.Date = Cate.GetString("date_on"); tempList.Title = Cate.GetString("title"); tempList.Text = Cate.GetString("text"); tempList.DateUpd = Cate.GetString("date_upd"); tempList.Type = Cate.GetString("type"); tempList.Status = Cate.GetString("status"); tempList.TimeFinish = Cate.GetString("time_finish"); tempList.Rating = Cate.GetString("rating"); tempList.Telefone = Cate.GetString("telephone"); tempList.Adress = Cate.GetString("adress"); tempList.Name = Cate.GetString("name"); listBids1.Add(tempList); } } catch { var temp1 = new ListBids(); temp1.Date = DateTime.Now.ToLongDateString(); temp1.Title = "Ошибка параметров"; listBids1.Add(temp1); } } catch { var temp1 = new ListBids(); temp1.Date = DateTime.Now.ToLongDateString(); temp1.Title = "Список пуст"; listBids1.Add(temp1); } return(listBids1); }
private void readWorldHierarchy(Dictionary <String, String> mapsItemsCodes, JSONArray continentsArray) { for (int i = 0; i < continentsArray.Length(); i++) { try { JSONObject currentContinentObject = continentsArray.GetJSONObject(i); if (currentContinentObject != null) { try { String currentContinentCode = currentContinentObject.GetString(CONTINENT_CODE_ID); if (currentContinentCode != null) { mapsItemsCodes.Add(currentContinentCode, ""); JSONArray countriesArray = null; try { countriesArray = currentContinentObject.GetJSONArray(COUNTRIES_ID); } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } if (countriesArray != null) { readCountriesHierarchy(mapsItemsCodes, currentContinentCode, countriesArray); } } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } } } catch (JSONException ex) { SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug); } } }
private MediaConstraints constraintsFromJSON(string jsonString) { if (jsonString == null) { return(null); } try { MediaConstraints constraints = new MediaConstraints(); JSONObject json = new JSONObject(jsonString); JSONObject mandatoryJSON = json.OptJSONObject("mandatory"); if (mandatoryJSON != null) { JSONArray mandatoryKeys = mandatoryJSON.Names(); if (mandatoryKeys != null) { for (int i = 0; i < mandatoryKeys.Length(); ++i) { string key = mandatoryKeys.GetString(i); string value = mandatoryJSON.GetString(key); constraints.Mandatory.Add(new MediaConstraints.KeyValuePair(key, value)); } } } JSONArray optionalJSON = json.OptJSONArray("optional"); if (optionalJSON != null) { for (int i = 0; i < optionalJSON.Length(); ++i) { JSONObject keyValueDict = optionalJSON.GetJSONObject(i); string key = keyValueDict.Names().GetString(0); string value = keyValueDict.GetString(key); constraints.Optional.Add(new MediaConstraints.KeyValuePair(key, value)); } } return(constraints); } catch (JSONException e) { throw new Exception("Error", e); } }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> public virtual void VerifyHsJobConf(JSONObject info, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job) { NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, info.Length()); WebServicesTestUtils.CheckStringMatch("path", job.GetConfFile().ToString(), info. GetString("path")); // just do simple verification of fields - not data is correct // in the fields JSONArray properties = info.GetJSONArray("property"); for (int i = 0; i < properties.Length(); i++) { JSONObject prop = properties.GetJSONObject(i); string name = prop.GetString("name"); string value = prop.GetString("value"); NUnit.Framework.Assert.IsTrue("name not set", (name != null && !name.IsEmpty())); NUnit.Framework.Assert.IsTrue("value not set", (value != null && !value.IsEmpty() )); } }
// Return the list of ICE servers described by a WebRTCPeerConnection // configuration string. private List <PeerConnection.IceServer> iceServersFromPCConfigJSON(string pcConfig) { try { JSONObject json = new JSONObject(pcConfig); JSONArray servers = json.GetJSONArray("iceServers"); List <PeerConnection.IceServer> ret = new List <PeerConnection.IceServer>(); for (int i = 0; i < servers.Length(); ++i) { JSONObject server = servers.GetJSONObject(i); string url = server.GetString("urls"); string credential = server.Has("credential") ? server.GetString("credential") : ""; ret.Add(new PeerConnection.IceServer(url, "", credential)); } return(ret); } catch (JSONException e) { throw new Exception("Error", e); } }
public async void FindOptimizaton(string source, string destrination)// ne radi otimizacija mora dugacije { client = new HttpClient(); // string default_for_every_query = "https://maps.googleapis.com/maps/api/directions/json?"; HttpResponseMessage response = await client.GetAsync("https://maps.googleapis.com/maps/api/directions/json?origin=" + source + "&destination=" + destrination + "&mode=transit&waypoints=optimize:true|Nikole Pasica, Serbia, Nis, 6&key=AIzaSyDY8RF7Oa9h5IeD7DX6l_GtGPnjT6J7k4U"); // if (response.StatusCode == HttpStatusCode.OK) { HttpContent content = response.Content; var json = await content.ReadAsStringAsync(); Console.WriteLine(json.ToString()); JSONObject jsonresoult = new JSONObject(json); JSONArray routesArray = jsonresoult.GetJSONArray("routes"); JSONObject routes = routesArray.GetJSONObject(0); JSONObject overviewPolylines = routes.GetJSONObject("overview_polyline"); String encodedString = overviewPolylines.GetString("points"); List <LatLng> list = decodePoly(encodedString); PolylineOptions po = new PolylineOptions(); //treba i < list.Count zasto puca sa tim? for (int i = 0; i < list.Count - 1; i++) { LatLng src = list.GetRange(i, 1)[0]; LatLng dest = list.GetRange(i + 1, 1)[0]; po.Add(src, dest).InvokeWidth(10);//.InvokeColor(SystemColors ; gmap.AddPolyline(po); } } }
public static List <string> GetCatalog() { Catalog = new JSONArray(Get(ActionGetCatalog)); var l_name_try = new List <string> (); try { for (int i = 0; i < Catalog.Length(); i++) { JSONObject Cate = Catalog.GetJSONObject(i); String name = Cate.GetString("cate_name"); var parent_id = Cate.GetInt("parent_cate"); if (parent_id == 0) { l_name_try.Add(name); } } } catch { return(l_name_try); } return(l_name_try); }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> private void VerifyClusterScheduler(JSONObject json) { NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject info = json.GetJSONObject("scheduler"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length()); info = info.GetJSONObject("schedulerInfo"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 6, info.Length()); VerifyClusterSchedulerGeneric(info.GetString("type"), (float)info.GetDouble("usedCapacity" ), (float)info.GetDouble("capacity"), (float)info.GetDouble("maxCapacity"), info .GetString("queueName")); JSONArray arr = info.GetJSONObject("queues").GetJSONArray("queue"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, arr.Length()); // test subqueues for (int i = 0; i < arr.Length(); i++) { JSONObject obj = arr.GetJSONObject(i); string q = CapacitySchedulerConfiguration.Root + "." + obj.GetString("queueName"); VerifySubQueue(obj, q, 100, 100); } }
// public void InitializeMap(String responseString) { try { JSONArray json = new JSONArray(responseString); for (int i = 0; i < json.Length(); i++) { JSONObject obj = json.GetJSONObject(i); string id_member = obj.GetString("id_member"); string fname_member = obj.GetString("fname_member"); string lname_member = obj.GetString("lname_member"); id_u = id_member; name_u = fname_member; lname_u = lname_member; } } catch (JSONException e) { e.StackTrace.ToString(); } }
public virtual void TestNodesQueryStateLost() { WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); MockNM nm2 = rm.RegisterNode("h2:1234", 5120); rm.SendNodeStarted(nm1); rm.SendNodeStarted(nm2); rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running); rm.NMwaitForState(nm2.GetNodeId(), NodeState.Running); rm.SendNodeLost(nm1); rm.SendNodeLost(nm2); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").QueryParam ("states", NodeState.Lost.ToString()).Accept(MediaType.ApplicationJson).Get <ClientResponse >(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject nodes = json.GetJSONObject("nodes"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length() ); JSONArray nodeArray = nodes.GetJSONArray("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, nodeArray.Length ()); for (int i = 0; i < nodeArray.Length(); ++i) { JSONObject info = nodeArray.GetJSONObject(i); string host = info.Get("id").ToString().Split(":")[0]; RMNode rmNode = rm.GetRMContext().GetInactiveRMNodes()[host]; WebServicesTestUtils.CheckStringMatch("nodeHTTPAddress", string.Empty, info.GetString ("nodeHTTPAddress")); WebServicesTestUtils.CheckStringMatch("state", rmNode.GetState().ToString(), info .GetString("state")); } }
//ParseData Method private Boolean ParseData() { try { JSONArray mJsonArray = new JSONArray(mJsonData); JSONObject mJsonObject; //new estate javalist mEstates = new JavaList <Estates>(); for (int i = 0; i < mJsonArray.Length(); i++) { mJsonObject = mJsonArray.GetJSONObject(i); //retrieve parsed data long id = mJsonObject.GetLong("estateId"); string name = mJsonObject.GetString("estateName"); string email = mJsonObject.GetString("estateEmail"); string telno = mJsonObject.GetString("estateTelNo"); int status = mJsonObject.GetInt("regStatus"); string added = mJsonObject.GetString("regdate"); //new instance of estates mEstate = new Estates(); mEstate.Id = id; mEstate.EstateName = name; mEstate.RegStatus = status; mEstate.RegDate = added; mEstates.Add(mEstate); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(false); }
public static Recipe FromJson(Context context, JSONObject json) { var recipe = new Recipe(); try { recipe.TitleText = json.GetString(Constants.RecipeFieldTitle); recipe.SummaryText = json.GetString(Constants.RecipeFieldSummary); if (json.Has(Constants.RecipeFieldImage)) { recipe.RecipeImage = json.GetString(Constants.RecipeFieldImage); } JSONArray ingredients = json.GetJSONArray(Constants.RecipeFieldIngredients); recipe.IngredientsText = ""; for (int i = 0; i < ingredients.Length(); i++) { recipe.IngredientsText += " - " + ingredients.GetJSONObject(i).GetString(Constants.RecipeFieldText) + "\n"; } JSONArray steps = json.GetJSONArray(Constants.RecipeFieldSteps); for (int i = 0; i < steps.Length(); i++) { var step = steps.GetJSONObject(i); var recipeStep = new RecipeStep(); recipeStep.StepText = step.GetString(Constants.RecipeFieldText); if (step.Has(Constants.RecipeFieldName)) { recipeStep.StepImage = step.GetString(Constants.RecipeFieldImage); } recipe.RecipeSteps.Add(recipeStep); } } catch (Exception ex) { Log.Error(Tag, "Error loading recipe: " + ex); return(null); } return(recipe); }
static bool filterData() { loadData = getData(); try { if (loadData != "" || loadData != null) { json_data = new JSONObject(loadData); switch (mFunction) { case "setUser": dataUser = json_data.GetString("Insert"); break; case "getUser": useronList = new List <Users>(); JSONArray resultJSON = json_data.GetJSONArray("results"); int count = resultJSON.Length(); for (int i = 0; i < count; i++) { JSONObject jsonNode = resultJSON.GetJSONObject(i); int Id = Convert.ToInt16(jsonNode.OptString("IdUser").ToString()); string Name = jsonNode.OptString("Name").ToString(); int Age = Convert.ToInt16(jsonNode.OptString("Age").ToString());; useronList.Add(new Users() { Id = Id, Name = Name, Age = Age }); } break; } } } catch (System.Exception) { throw; } return(true); }