public List<List<UpdateInfo>> parseJSONMark8(String strResult) throws NumberFormatException, JSONException { List<List<UpdateInfo>> perlist = new ArrayList<List<UpdateInfo>>(); JSONObject jsonObj = new JSONObject(strResult); if (jsonObj.getInt("error") != 1) { JSONObject result = jsonObj.getJSONObject("result"); JSONArray udArray = new JSONArray(result.getString("ResultINFO")); for (int i = 0; i < udArray.length(); i++) { List<UpdateInfo> list = new ArrayList<UpdateInfo>(); JSONObject jsonUd = (JSONObject) udArray.get(i); JSONArray contactArray = jsonUd.getJSONArray("contact"); for (int j = 0; j < contactArray.length(); j++) { JSONObject contactObj = (JSONObject) contactArray.get(j); UpdateInfo info = new UpdateInfo( jsonUd.getString("account"), contactObj.getInt("mark"), contactObj.getString("contact")); info.setName(jsonUd.getString("name")); list.add(info); } perlist.add(list); } } return perlist; }
/* * Sample url * http://maps.googleapis.com/maps/api/directions/json?origin=pune * &destination=amravati&sensor=false&mode=driving * * result{ "routes" : [{ "bounds" : { "northeast" : { "lat" : 20.92891 "lng" * : 77.764730 }, "southwest" : { "lat" : 18.520650,"lng" : 73.856740 } * "copyrights" : "Map data ©2013 Google", "legs" : [ { "distance" : { * "text" : "603 km", "value" : 602864 }, "duration" : { "text" : * "10 hours 1 min", "value" : 36060 }, "end_address" : * "Amravati, Maharashtra, India", "end_location" : { "lat" : 20.925830, * "lng" : 77.764730 }, "start_address" : "Pune, Maharashtra, India", * "start_location" : { "lat" : 18.520650, "lng" : 73.856740 }, */ public static String getlocationCity(double lat, double lonng) { String location = ""; JSONArray ja; String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lonng + "&sensor=true"; StringBuffer json = StringHelper.readURLContent(url); try { System.out.println("URL " + url); JSONObject myjson = new JSONObject(json.toString()); ja = (JSONArray) myjson.get("results"); JSONArray add = (JSONArray) ((JSONObject) ja.get(0)).get("address_components"); JSONObject city = (JSONObject) add.get(4); location = city.getString("long_name"); System.out.println("......................................" + location); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return location; }
private void parseData(String data) { try { JSONObject boardArrayData = new JSONObject(data); currentTurn = boardArrayData.getInt("turn"); players = new LinkedList<>(); JSONArray playersList = new JSONArray(boardArrayData.get("players_list").toString()); for (int i = 0; i < playersList.length(); i++) { JSONObject obj = playersList.optJSONObject(i); players.add( new Player( PlayerType.values()[obj.getInt("type")], obj.getString("name"), obj.getInt("image"))); } JSONArray rowArray = new JSONArray(boardArrayData.get("double_array").toString()); JSONArray coloumArray = new JSONArray(rowArray.get(0).toString()); int rowLength = rowArray.length(); int coloumLength = coloumArray.length(); arrayOfBoard = new Integer[rowLength][coloumLength]; for (int i = 0; i < rowLength; i++) { coloumArray = new JSONArray(rowArray.get(i).toString()); for (int j = 0; j < coloumArray.length(); j++) { arrayOfBoard[i][j] = coloumArray.getInt(j); } } } catch (JSONException e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("usage: one configure file is needed"); System.exit(0); } Properties conf = ConfProperties.getProperties(args[0]); URL cityList = new URL(conf.getProperty("city.URL")); BufferedReader in = new BufferedReader(new InputStreamReader(cityList.openStream())); String result = in.readLine(); String[] tmp = result.split(":"); JSONArray res_arr = new JSONArray(tmp[1]); java.sql.Connection conn = DriverManager.getConnection( conf.getProperty("db.name"), conf.getProperty("db.user"), conf.getProperty("db.password")); java.sql.Statement stmt = conn.createStatement(); for (int i = 0; i < res_arr.length(); i++) { String sql = "insert into City(cityNameCh) values('" + res_arr.get(i) + "')"; System.out.println(sql); if (!checkCity(res_arr.get(i).toString(), conf)) { System.out.println(res_arr.get(i).toString()); stmt.executeUpdate(sql); } } stmt.close(); conn.close(); }
static void writeJSON(Appendable sb, JSONArray jo, int indentFactor, int indent) throws Exception { int len = jo.length(); if (len == 0) { sb.append("[]"); return; } int i; sb.append("["); if (len == 1) { writeJSONValue(sb, jo.get(0), indentFactor, indent); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } writeJSONValue(sb, jo.get(i), indentFactor, newindent); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); }
// 获取树 private String getRoleDatarangeTree() { JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonObject.put("id", "root"); jsonObject.put("pId", ""); jsonObject.put("name", "范围"); jsonObject.put("open", true); jsonArray.put(jsonObject); // JSONArray dataArray = dataContainerService.getDataContainerTree(); JSONArray datarangeArray = datarangeService.getDatarangeRootTree(); JSONArray queueArray = QueueManager.getQueueTree(); // JSONArray customerPoolsArray = customerPoolService.getPoolsTree(); // for(int i = 0; i < dataArray.length(); i++) { // jsonArray.put(dataArray.get(i)); // } for (int i = 0; i < datarangeArray.length(); i++) { jsonArray.put(datarangeArray.get(i)); } for (int i = 0; i < queueArray.length(); i++) { jsonArray.put(queueArray.get(i)); } // for(int i = 0; i < customerPoolsArray.length(); i++) { // jsonArray.put(customerPoolsArray.get(i)); // } // return jsonArray.toString(); }
protected List<List<Object>> getAllStackableJSONPoolsDataAsListOfLists() throws Exception { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; Map<String, List<JSONObject>> stackableJSONPoolsMap = new HashMap<String, List<JSONObject>>(); for (List<Object> row : getAllJSONPoolsDataAsListOfLists()) { JSONObject jsonPool = (JSONObject) row.get(0); // loop through all the productAttributes looking for stacking_id JSONArray jsonProductAttributes = jsonPool.getJSONArray("productAttributes"); for (int j = 0; j < jsonProductAttributes.length(); j++) { // loop product attributes to find a stacking_id if (((JSONObject) jsonProductAttributes.get(j)).getString("name").equals("stacking_id")) { String stacking_id = ((JSONObject) jsonProductAttributes.get(j)).getString("value"); // we found a stackable pool, let's add it to the stackableJSONPoolsMap if (!stackableJSONPoolsMap.containsKey(stacking_id)) stackableJSONPoolsMap.put(stacking_id, new ArrayList<JSONObject>()); stackableJSONPoolsMap.get(stacking_id).add(jsonPool); break; } } } for (String stacking_id : stackableJSONPoolsMap.keySet()) { List<JSONObject> stackableJSONPools = stackableJSONPoolsMap.get(stacking_id); ll.add(Arrays.asList(new Object[] {stackableJSONPools})); } return ll; }
public static int[] getTimeAndDistanceByCoord( double latX, double lonX, double latY, double lonY) { String distanceFeed = null; int ret[] = new int[2]; try { distanceFeed = GeocodeService.getJSONDistance(latX, lonX, latY, lonY); JSONObject ja = new JSONObject(distanceFeed); if (ja.get("origin_addresses").equals("[\"Zakinthos, Greece\"]") || ja.get("destination_addresses").equals("[\"Zakinthos, Greece\"]")) { System.out.println("first if problem"); return null; } JSONArray rows = (JSONArray) ja.get("rows"); if (rows.length() == 0) { System.out.println("rows -1"); return null; } JSONObject elmnts = (JSONObject) rows.get(0); JSONArray infoArr = (JSONArray) elmnts.get("elements"); if (infoArr.length() == 0) { System.out.println("info arr -1"); return null; } JSONObject infoJson = (JSONObject) infoArr.get(0); ret[0] = Integer.parseInt(((JSONObject) infoJson.get("distance")).get("value").toString()); ret[1] = Integer.parseInt(((JSONObject) infoJson.get("duration")).get("value").toString()); return ret; } catch (Exception e) { e.printStackTrace(); return null; } }
private void testPredictDiabetes(boolean skipDecoding) throws MLHttpClientException, JSONException { String payload = "[[1,89,66,23,94,28.1,0.167,21],[2,197,70,45,543,30.5,0.158,53]]"; String url = skipDecoding ? "/api/models/" + modelId + "/predict?skipDecoding=true" : "/api/models/" + modelId + "/predict"; response = mlHttpclient.doHttpPost(url, payload); assertEquals( "Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); String reply = mlHttpclient.getResponseAsString(response); JSONArray predictions = new JSONArray(reply); assertEquals( "Expected 2 predictions but received only " + predictions.length(), 2, predictions.length()); if (skipDecoding) { assertEquals( "Expected a double value but found " + predictions.get(0), true, predictions.get(0) instanceof Double); assertEquals( "Expected a double value but found " + predictions.get(1), true, predictions.get(1) instanceof Double); } }
public List<OBOClass> runSciGraphTaxonRequest(String req) { JSONArray responseJSON = sendRequest(req); List<OBOClass> taxonMap = new ArrayList<OBOClass>(); Set<String> seenID = new HashSet<String>(); for (int i = 0; i < responseJSON.length(); i++) { JSONObject jsonObj = (JSONObject) responseJSON.get(i); JSONObject tokenObj = jsonObj.getJSONObject("token"); String id = tokenObj.getString("id"); if (seenID.contains(id)) continue; JSONArray terms = tokenObj.getJSONArray("terms"); String prefix = id.substring(0, id.indexOf(":")); seenID.add(id); if (prefix.equals("VTO")) { // Ignore NCBITaxon for (int j = 0; j < terms.length(); j++) { String term = (String) terms.get(j); taxonMap.add(new OBOClassImpl(term, id)); } } } return taxonMap; }
public static String[] getCitys(String province, JSONArray jsonArray) { String[] citys; JSONArray city_jsonArray = null; JSONObject jo = null; for (int i = 0; i < jsonArray.length(); i++) { try { jo = (JSONObject) jsonArray.get(i); if (jo.getString("name").toString().equals(province)) { city_jsonArray = (JSONArray) jo.get("citys"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } citys = new String[city_jsonArray.length()]; for (int j = 0; j < city_jsonArray.length(); j++) { try { String[] strs = city_jsonArray.get(j).toString().split("[:]"); String temp_str = strs[1]; temp_str = temp_str.substring(temp_str.indexOf("\"") + 1, temp_str.lastIndexOf("\"")); // citys[j] = city_jsonArray.get(j).toString(); citys[j] = temp_str; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return citys; }
private Double[] convertJSONArray(JSONArray arr) { Double[] rbuf = new Double[arr.length()]; for (int i = 0; i < arr.length(); i++) { if (arr.get(i) instanceof Integer) rbuf[i] = ((Integer) arr.get(i)).doubleValue(); else rbuf[i] = (Double) arr.get(i); } return rbuf; }
/** * After View created * * @param view * @param savedInstanceState */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(true); mAdapter = new RecyclerViewMaterialAdapter(new FaqRecyclerViewAdapter(mContentItems)); // loop through each faq in JSON Array and do frontend stuff! for (int i = 0; i < faqsArray.length(); i++) { FaqInfo item = new FaqInfo(); try { // parsing array into String Log.i(TAG, "populating item!"); item.question = (String) ((JSONObject) faqsArray.get(i)).get(QUESTION_QUERY); item.answer = (String) ((JSONObject) faqsArray.get(i)).get(ANSWER_QUERY); } catch (JSONException e) { e.printStackTrace(); } mContentItems.add(item); } // static cards // FaqInfo item1 = new FaqInfo(); // item1.question = "Where/when to submit my hack?"; // item1.answer = "All hacks must submitted to ChallengePost\n" + // "www.challengepost.com/HackingEDU by 9:30am\n" + // " on Sunday in order to be eligible for prizes."; // mContentItems.add(item1); // // FaqInfo item2 = new FaqInfo(); // item2.question = "Who can help me with coding? "; // item2.answer = "Anyone with a HackingEDU Staff shirt can connect\n" + // "you with a sponsor or experience team member \n" + // "depending on the language or framework."; // mContentItems.add(item2); // // FaqInfo item3 = new FaqInfo(); // item3.question = "Can someone help me with Git?"; // item3.answer = "Look for Vivek Vinodh, the tall,dark, and handsome \n" + // "Indian guy. He is the Git master. He should be \n" + // "sleeping in the stands right now."; // mContentItems.add(item3); // // FaqInfo item4 = new FaqInfo(); // item4.question = "Can someone help me with Git?"; // item4.answer = "Look for Vivek Vinodh, the tall,dark, and handsome \n" + // "Indian guy. He is the Git master. He should be \n" + // "sleeping in the stands right now."; // mContentItems.add(item4); mAdapter.notifyDataSetChanged(); mRecyclerView.setAdapter(mAdapter); MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null); }
protected void compareJSONArrayWithStrictOrder( String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException { for (int i = 0; i < expected.length(); ++i) { Object expectedValue = expected.get(i); Object actualValue = actual.get(i); compareValues(key + "[" + i + "]", expectedValue, actualValue, result); } }
public static String[] getLocation(String address) { String addresspincode[] = new String[2]; String add = " "; String pincode = " "; String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + address + "&sensor=true"; try { System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if (address.equalsIgnoreCase("0.0,0.0")) { add = ""; addresspincode[0] = add; addresspincode[1] = pincode; return addresspincode; } System.out.println("URL " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; StringBuffer json = new StringBuffer(); int statusCode = -1; while ((line = in.readLine()) != null) json.append(line); JSONArray ja; JSONObject myjson = new JSONObject(json.toString()); // ja = new JSONArray(json.toString()); ja = (JSONArray) myjson.get("results"); // myjson = new JSONObject(json.toString()); myjson.get("results"); Object last = ((JSONObject) ja.get(0)).get("formatted_address"); JSONArray jarray = (JSONArray) (((JSONObject) ja.get(0)).get("address_components")); for (int i = 0; i < jarray.length(); i++) { JSONObject jo = jarray.getJSONObject(i); JSONArray types = (JSONArray) jo.get("types"); for (int j = 0; j < types.length(); j++) { if (types.getString(0).equalsIgnoreCase("postal_code")) { pincode = jo.get("long_name").toString(); break; } } } System.out.println(last); System.out.println("pincode " + pincode); add = last.toString(); System.out.println("Final adrress is---" + add); addresspincode[0] = add; addresspincode[1] = pincode; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return addresspincode; }
@Override public boolean execute(String action, JSONArray args, CallbackContext cbContext) throws JSONException { try { Method[] list = this.getClass().getMethods(); Method methodToExecute = null; for (Method method : list) { if (method.getName().equals(action)) { Type[] types = method.getGenericParameterTypes(); if (args.length() + 1 == types.length) { // +1 is the cbContext boolean isValid = true; for (int i = 0; i < args.length(); i++) { Class arg = args.get(i).getClass(); if (types[i] == arg) { isValid = true; } else { isValid = false; break; } } if (isValid) { methodToExecute = method; break; } } } } if (methodToExecute != null) { Type[] types = methodToExecute.getGenericParameterTypes(); Object[] variableArgs = new Object[types.length]; for (int i = 0; i < args.length(); i++) { variableArgs[i] = args.get(i); } variableArgs[variableArgs.length - 1] = cbContext; Class<?> r = methodToExecute.getReturnType(); if (r == boolean.class) { return (Boolean) methodToExecute.invoke(this, variableArgs); } else { methodToExecute.invoke(this, variableArgs); return true; } } else { return false; } } catch (IllegalAccessException e) { e.printStackTrace(); return false; } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (InvocationTargetException e) { e.printStackTrace(); return false; } }
/** * Jason object/array object compare * * @param obj1 * @param obj2 * @return * @throws JSONException */ public static boolean jsonsEqual(Object obj1, Object obj2) throws JSONException { if (!obj1.getClass().equals(obj2.getClass())) { return false; } if (obj1 instanceof JSONObject) { JSONObject jsonObj1 = (JSONObject) obj1; JSONObject jsonObj2 = (JSONObject) obj2; String[] names = JSONObject.getNames(jsonObj1); String[] names2 = JSONObject.getNames(jsonObj2); if (names.length != names2.length) { return false; } for (String fieldName : names) { Object obj1FieldValue = jsonObj1.get(fieldName); Object obj2FieldValue = jsonObj2.get(fieldName); if (!jsonsEqual(obj1FieldValue, obj2FieldValue)) { return false; } } } else if (obj1 instanceof JSONArray) { JSONArray obj1Array = (JSONArray) obj1; JSONArray obj2Array = (JSONArray) obj2; if (obj1Array.length() != obj2Array.length()) { return false; } for (int i = 0; i < obj1Array.length(); i++) { boolean matchFound = false; for (int j = 0; j < obj2Array.length(); j++) { if (jsonsEqual(obj1Array.get(i), obj2Array.get(j))) { matchFound = true; break; } } if (!matchFound) { return false; } } } else { if (!obj1.equals(obj2)) { return false; } } return true; }
private static boolean deepEqualArrays(final JSONArray arr1, final JSONArray arr2) { if (arr1.length() != arr2.length()) { return false; } for (int i = 0; i < arr1.length(); ++i) { if (!deepEquals(arr1.get(i), arr2.get(i))) { return false; } } return true; }
/** create a jsonarray and store it in sharedpreference for use later. Store last 10 results */ public void fillScores() { SharedPreferences scores = getSharedPreferences(PREFS_NAME, 0); JSONArray jsonArray = null; JSONObject jsonObj = new JSONObject(); boolean modifiedExistingEntry = false; try { jsonObj.put("time", sessionTimeStamp); jsonObj.put("X", mXWinCount); jsonObj.put("O", mOWinCount); jsonArray = new JSONArray(scores.getString("scores", "[]")); int length = jsonArray.length(); Log.i(getLocalClassName(), "json length=" + String.valueOf(jsonArray.length())); for (int i = 0; i < jsonArray.length(); i++) { // Log.i(getLocalClassName(), String.valueOf(i) + "th json= " + // jsonArray.get(i).toString()); Log.i( getLocalClassName(), "::" + sessionTimeStamp + "::" + ((JSONObject) (jsonArray.get(i))).getString("time") + "::"); if (sessionTimeStamp.equalsIgnoreCase( ((JSONObject) (jsonArray.get(i))).getString("time"))) { ((JSONObject) (jsonArray.get(i))).put("X", mXWinCount); ((JSONObject) (jsonArray.get(i))).put("O", mOWinCount); modifiedExistingEntry = true; break; } } if (!modifiedExistingEntry) { if (length < 9) { jsonArray.put(jsonObj); } else { int i = 1; for (i = 1; i < 9; i++) { jsonArray.put(i - 1, (JSONObject) jsonArray.get(i)); } jsonArray.put(i - 1, jsonObj); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } SharedPreferences.Editor editor = scores.edit(); editor.putString("scores", jsonArray.toString()); editor.commit(); }
public static ArrayList<Notification> parseNotifications(JSONArray jnotifications) throws JSONException { ArrayList<Notification> notifications = new ArrayList<Notification>(); for (int i = 0; i < jnotifications.length(); i++) { if (!(jnotifications.get(i) instanceof JSONObject)) continue; JSONObject jgroup = (JSONObject) jnotifications.get(i); Notification n = Notification.parse(jgroup); if (n != null) notifications.add(n); } return notifications; }
public static HashMap getDIstanceTimeDetails(String srcLocationName, String destLocationName) { String[] startlatlong = new String[2]; String[] endlatlong = new String[2]; HashMap<String, Object> dataMap = new HashMap(); String distance = ""; String time = ""; srcLocationName = URLEncoder.encode(srcLocationName); destLocationName = URLEncoder.encode(destLocationName); String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + srcLocationName + "&destination=" + destLocationName + "&sensor=false&mode=driving"; JSONArray ja; try { System.out.println("URL " + url); StringBuffer json = StringHelper.readURLContent(url); JSONObject myjson = new JSONObject(json.toString()); ja = (JSONArray) myjson.get("routes"); JSONArray legs = (JSONArray) ((JSONObject) ja.get(0)).get("legs"); JSONObject last = (JSONObject) legs.get(0); JSONObject distanceObject = (JSONObject) last.get("distance"); distance = distanceObject.getString("text"); System.out.println("distanceeeeeeeeeee " + distance); JSONObject durationObject = (JSONObject) last.get("duration"); time = durationObject.getString("text"); } catch (Exception e) { e.printStackTrace(); endlatlong[0] = "-1"; endlatlong[1] = "-1"; startlatlong[0] = "-1"; startlatlong[1] = "-1"; distance = "-1"; time = "-1"; } finally { dataMap.put("START_LATLNG", startlatlong); dataMap.put("END_LATLNG", endlatlong); dataMap.put("DISTANCE", distance); dataMap.put("TIME", time); System.out.println("Test for Source lat long " + dataMap); } return dataMap; }
@Test public void historyCount5Reverse() { try { JSONArray response = (JSONArray) pubnub.history(channel, 5, true); JSONArray messages = (JSONArray) response.get(0); assertEquals(messages.length(), 5); assertEquals(messages.get(0), message + "0"); assertEquals(messages.get(4), message + "4"); } catch (Exception e) { fail("Exception " + e.toString()); } }
@Override public void onBindViewHolder(BierHolder holder, int position) { JSONObject jso = null; try { jso = (JSONObject) x.get(position); Log.d("TAG", "wa lhmar" + x.get(position)); holder.mTextView.setText(jso.getString("name")); holder.description.setText(jso.getString("description")); holder.id.setText(jso.getString("id")); } catch (JSONException e) { e.printStackTrace(); } }
@Override public Object parser(JSONObject json) { if (json != null) { try { // 判断是成功 JSONObject opret = json.getJSONObject("opret"); int opflag = opret.getInt("opflag"); if (opflag != 1) { return null; } ArrayList<ShopRankingInfo> shopRankingList = new ArrayList<ShopRankingInfo>(); // 解析排行版总分类 JSONArray catranksJsonArray = json.getJSONArray("catranks"); int catranksSize = catranksJsonArray.length(); for (int i = 0; i < catranksSize; i++) { ShopRankingInfo rankingInfo = new ShopRankingInfo(); JSONObject rankJSONObject = (JSONObject) catranksJsonArray.get(i); rankingInfo.mId = rankJSONObject.optInt("categoryid"); rankingInfo.mParentid = rankJSONObject.optInt("parentid"); rankingInfo.mName = rankJSONObject.optString("categoryname"); rankingInfo.mIconUrl = rankJSONObject.optString("categoryfavicon"); // 解析包含的子类 ArrayList<ShopRankingChildInfo> childList = new ArrayList<ShopRankingChildInfo>(); JSONArray childJsonArray = rankJSONObject.getJSONArray("ranks"); int ranksSize = childJsonArray.length(); for (int j = 0; j < ranksSize; j++) { ShopRankingChildInfo childInfo = new ShopRankingChildInfo(); JSONObject childJSONObject = (JSONObject) childJsonArray.get(j); childInfo.mId = childJSONObject.optInt("catrankid"); childInfo.mName = childJSONObject.optString("catrankname"); childInfo.mIconUrl = childJSONObject.optString("catrankfavicon"); childList.add(childInfo); } rankingInfo.mChildList = childList; shopRankingList.add(rankingInfo); } return shopRankingList; // return parseRankListData(shopRankingList); } catch (Exception e) { e.printStackTrace(); } } return null; }
public void LoadSeedData(String strColl, String metadatafile) throws Exception { try { InputStream is = this.getClass().getResourceAsStream(metadatafile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull("ReferralWireSeedData")) { JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData"); DBCollection dbcoll = store.getColl(strColl); Object coll = (Object) json.get(strColl); if (coll instanceof JSONArray) { JSONArray defs = (JSONArray) coll; for (int i = 0; i < defs.length(); i++) { Object obj = (JSONObject) defs.get(i); dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString())); } } else { dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
private String[] parseJSONData(String result) { String zipCodeArray[] = null; try { JSONObject jsonObj = new JSONObject(result); JSONArray arrayList = (JSONArray) jsonObj.get("postalCodes"); zipCodeArray = new String[arrayList.length()]; String zipCode = null; int iActualCount = 0; for (int iIndexCount = 0; iIndexCount <= arrayList.length(); ++iIndexCount) { try { zipCode = (String) ((JSONObject) arrayList.get(iIndexCount)).get("postalCode"); zipCodeArray[iActualCount] = zipCode; ++iActualCount; } catch (org.json.JSONException e) { e.printStackTrace(); } } } catch (org.json.JSONException e) { e.printStackTrace(); } return zipCodeArray; }
public static ArrayList<FeedItem> parseJsonFeed(JSONObject response) { ArrayList<FeedItem> mFeedItems = new ArrayList<FeedItem>(); Log.d("response", String.valueOf(response)); try { JSONArray feedArray = response.getJSONArray("feed"); for (int i = 0; i < feedArray.length(); i++) { JSONObject feedObj = (JSONObject) feedArray.get(i); FeedItem item = new FeedItem(); item.setId(feedObj.getInt("id")); item.setName(feedObj.getString("name")); // Image might be null sometimes String image = feedObj.isNull("image") ? null : feedObj.getString("image"); item.setImage(image); item.setStatus(feedObj.getString("status")); item.setProfilePic(feedObj.getString("profilePic")); item.setTimeStamp(feedObj.getString("timeStamp")); // url might be null sometimes String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url"); item.setUrl(feedUrl); mFeedItems.add(item); } } catch (JSONException e) { e.printStackTrace(); } return mFeedItems; }
public String getUserFollowers() { OAuthRequest request = new OAuthRequest(Verb.GET, GET_FOLLOWERS_URL); this.service.signRequest(twToken.getAccessToken(), request); Response response = request.send(); JSONObject res = null; JSONObject followers = new JSONObject(); JSONArray followersList = new JSONArray(); try { res = new JSONObject(response.getBody()); JSONArray followersIDList = res.getJSONArray("ids"); JSONObject other = null; for (int i = 0; i < followersIDList.length(); i++) { // System.out.println(friendsIDList.get(i).toString()); other = getOtherProfileJson(followersIDList.get(i).toString()); // System.out.println(other); if (!other.toString().contains("No user matches for specified terms")) followersList.put(other); followers.put("friends", followersList); } } catch (JSONException e) { response.getBody(); } if (res != null) // return res.toJSONString(); return followers.toString(); else return null; }
@Override protected void onPostExecute(String result) { super.onPostExecute(result); try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = new JSONArray(); Iterator iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = (String) iterator.next(); if (key != "") { jsonArray.put(jsonObject.get(key)); MyCurrencyObject object = new MyCurrencyObject(); object.setNameId(key); object.setFullCountryName(jsonObject.get(key).toString()); MyCurrencyObjArray.addCurrencyObj(object); } } MainActivity.countriesList.clear(); for (int i = 0; i < jsonArray.length(); i++) { MainActivity.countriesList.add(jsonArray.get(i).toString()); } complete.asyncComplete1(true); } catch (JSONException e) { e.printStackTrace(); } }
@Override protected List<Repository> doInBackground(Void... params) { List<Repository> repositories = new ArrayList<>(); try { JSONObject responseObject = new ApiClient() .addAuthHeader() .setUrl(ApiClient.GET_CURRENT_USER_REPOS_URL) .asArray() .executeGet(); if (responseObject.optInt(ApiClient.STATUS_CODE) != ApiClient.STATUS_CODE_OK) { cancel(true); return null; } JSONArray array = (JSONArray) responseObject.get(ApiClient.LIST_DATA_KEY); for (int i = 0; i < array.length(); i++) { repositories.add(new Repository(((JSONObject) array.get(i)).getString("name"))); } } catch (IOException | JSONException e) { e.printStackTrace(); } return repositories; }