List of usage examples for org.json JSONArray length
public int length()
From source file:com.appdynamics.demo.gasp.fragment.TwitterResponderFragment.java
private static List<String> getTweetsFromJson(String json) { ArrayList<String> tweetList = new ArrayList<String>(); try {/*from w w w . ja va 2 s.c om*/ JSONObject tweetsWrapper = (JSONObject) new JSONTokener(json).nextValue(); JSONArray tweets = tweetsWrapper.getJSONArray("statuses"); for (int i = 0; i < tweets.length(); i++) { JSONObject tweet = tweets.getJSONObject(i); Log.d(TAG, "Tweet: " + tweet.getString("text")); tweetList.add(tweet.getString("text")); } } catch (JSONException e) { Log.e(TAG, "Failed to parse JSON.", e); } return tweetList; }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.parser.platform.PlatformChain.java
public PlatformChain(JSONObject json, PlatformModel platform) throws CiliaException { super(getJSONname(json)); this.platform = platform; this.refArchitectureID = null; PlatformID platformId = platform.getPlatformID(); String chainId = getName();/*ww w . j av a 2 s. c om*/ try { JSONArray mediatorsList = json.getJSONArray("Mediators"); for (int i = 0; i < mediatorsList.length(); i++) { String mediatorName = (String) mediatorsList.get(i); JSONObject jsonNode = CiliaRestHelper.getMediatorContent(platform.getPlatformID(), getName(), mediatorName); String state = jsonNode.getString("State"); String type = jsonNode.getString("Type"); String namespace = jsonNode.getString("Namespace"); NameNamespaceID mediatorTypeID = new NameNamespaceID(type, namespace); mediators.add(new MediatorInstanceRef(mediatorName, mediatorTypeID, state, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing mediators list", e); } try { JSONObject adaptersRoot = json.getJSONObject("Adapters"); if (adaptersRoot.has("in-only")) { JSONArray inAdaptersList = adaptersRoot.getJSONArray("in-only"); for (int i = 0; i < inAdaptersList.length(); i++) { String adapterName = (String) inAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("out-only")) { JSONArray outAdaptersList = adaptersRoot.getJSONArray("out-only"); for (int i = 0; i < outAdaptersList.length(); i++) { String adapterName = (String) outAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("in-out")) { JSONArray inOutAdaptersList = adaptersRoot.getJSONArray("in-out"); for (int i = 0; i < inOutAdaptersList.length(); i++) { String adapterName = (String) inOutAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("unknown")) { JSONArray unknownAdaptersList = adaptersRoot.getJSONArray("unknown"); for (int i = 0; i < unknownAdaptersList.length(); i++) { String adapterName = (String) unknownAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } try { JSONArray bindingsList = json.getJSONArray("Bindings"); for (int i = 0; i < bindingsList.length(); i++) { JSONObject binding = (JSONObject) bindingsList.get(i); bindings.add(new BindingInstance(binding, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } }
From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java
/** * Parses the JSON-String to a list of {@link Muscle}s. * /*from w w w .j av a 2 s . c o m*/ * Example for such a .json File: * * [{ * "de": { "name" : "Bizeps" }, * "en": { "name" : "Biceps", "alternative_names":["Biceps muscle"] } * }, ...] * * @param jsonString The String to parse. * * @return A list of {@link Muscle}s, null if an Error occurs.. * */ @Override public List<Muscle> parse(String jsonString) { List<Muscle> muscleList = new ArrayList<Muscle>(); JSONArray jsonArray; try { jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject muscleObject = jsonArray.getJSONObject(i); Muscle m = null; for (String locale : TAG_LOCALES) { if (muscleObject.has(locale)) { JSONObject languageObject = muscleObject.getJSONObject(locale); // name String name = languageObject.getString(TAG_NAME); // first name is primary name, all other names are alternative names List<String> nameList = new ArrayList<String>(); nameList.add(name); // alternative names if (languageObject.has(TAG_ALTERNATIVE_NAMES)) { JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES); String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray); for (int t = 0; t < alternativeNameArray.length; t++) { String altName = alternativeNameArray[t]; nameList.add(altName); } } if (m == null) { m = new Muscle(new Locale(locale), nameList); } else { m.addNames(new Locale(locale), nameList); } } } // Log.d(TAG, "Finished parsing Muscle: \n" + m.toDebugString()); muscleList.add(m); } } catch (JSONException e) { Log.e(TAG, "Error during parsing JSON File.", e); return null; } if (muscleList.isEmpty()) throw new AssertionError("JSON parsing failed: no muscles parsed."); return muscleList; }
From source file:com.util.httpRecargas.java
public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) { // System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;// w w w .ja va 2 s. c om try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8"); data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8"); data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8"); data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString()); // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); // JSONArray dataJson = new JSONArray(); // dataJson = objJason.getJSONArray("data"); String jdata = objJason.optString("data"); String mensaje = objJason.optString("message"); System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje); // System.out.println(" el objeto jdata es " + jdata); objJason = new JSONObject(jdata); // System.out.println("objeto normal 1 " + objJason.toString()); // jdata = objJason.optString("items"); // System.out.println("\n\n el objeto jdata es " + jdata); JSONArray jsonArray = new JSONArray(); Gson gson = new Gson(); //objJason = gson.t jsonArray = objJason.getJSONArray("items"); // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString()); /* List<String> list = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(String.valueOf(i)); list.add(jsonArray.getJSONObject(i).getString("created_date")); list.add(jsonArray.getJSONObject(i).getString("description")); list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); list.add(jsonArray.getJSONObject(i).getString("before_balance")); list.add(jsonArray.getJSONObject(i).getString("after_balance")); } System.out.println("\n\nel array java contiene "+ list.toString()); */ List<Recarga> recargas = new ArrayList<Recarga>(); for (int i = 0; i < jsonArray.length(); i++) { Recarga recarga = new Recarga(); recarga.setNo(i); recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date")); recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description")); recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance")); recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance")); recargas.add(recarga); } for (int i = 0; i < recargas.size(); i++) { System.out.print("\n\nNo" + recargas.get(i).getNo()); System.out.print("\nFecna " + recargas.get(i).getFecha()); System.out.print("\nDescripcion " + recargas.get(i).getDescripcion()); System.out.print("\nMonto " + recargas.get(i).getMonto()); System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior()); System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior()); } return recargas; }
From source file:com.zotoh.core.json.JUT.java
@Test public void testFromString() throws Exception { JSONObject top = JSONUte.read(jsonStr()); JSONArray a; JSONObject obj;//from w w w . j a va 2s. c o m assertTrue(top != null); assertTrue("hello".equals(top.getString("a"))); assertTrue("world".equals(top.getString("b"))); a = top.getJSONArray("c"); assertTrue(a != null); assertTrue(a.length() == 2); assertTrue(a.get(0).equals(true)); assertTrue(a.get(1).equals(false)); obj = top.getJSONObject("d"); assertTrue(obj != null); }
From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java
/** * load result list from json response for given feed * * @param results/*from w w w.java2s .c o m*/ * @param resultArray * @param feedName * @param <T> * @throws Exception */ private <T> void loadResults(LinkedList<T> results, JSONArray resultArray, String feedName) throws Exception { for (int i = 0; i < resultArray.length(); i++) { results.add((T) GraphObjectFactory.getObject(feedName, (JSONObject) resultArray.get(i))); } }
From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java
private void parsePagePosts(GraphObject result, FacebookRequestError error) { String title = null;// ww w . j a va2 s .c o m String alertMessage = null; if (error == null) { Log.d("facebookfoo ###############", "retrievig posts success"); try { JSONArray page_posts = result.getInnerJSONObject().getJSONArray("data"); Log.d("facebookfoo ###############", "retrievig user posts length : " + page_posts.length()); for (int i = 0; i < page_posts.length(); i++) { Log.d("facebookfoo ##############", "post id : " + i); JSONObject item = page_posts.getJSONObject(i); String post_id = item.getString("id"); //Log.d("facebookfoo ##############", "post id : " + post_id); String story = item.getString("story"); //Log.d("facebookfoo ##############","story : " + story); String message = item.getString("type"); //Log.d("facebookfoo ##############","type : " + message); String updated_time = item.getString("updated_time"); // Log.d("facebookfoo ##############","updated_time : " + updated_time); //boolean ispublished = item.getString("") if (!postsTable.containsKey(post_id)) { postsTable.put(post_id, new PostsRecord(post_id, story, message, updated_time, true)); } // Log.d("facebookfoo ##############","is_published : " + ); } } catch (Exception e) { } } else { Log.d("facebookfoo ###############", "retrievig page posts fail"); } }
From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java
private void parseUserPages(GraphObject result, FacebookRequestError error) { String title = null;/* w w w .j a v a 2 s. c om*/ String alertMessage = null; if (error == null) { Log.d("facebookfoo ###############", "retrievig user pages success"); try { JSONArray user_pages = result.getInnerJSONObject().getJSONArray("data"); for (int i = 0; i < user_pages.length(); i++) { JSONObject item = user_pages.getJSONObject(i); page_id = item.getString("id"); Log.d("facebookfoo ##############", "id : " + page_id); Log.d("facebookfoo ##############", "category : " + item.getString("category")); Log.d("facebookfoo ##############", "perms : " + item.getString("perms")); String accessToken = item.getString("access_token"); if (accessToken != null) { Log.d("facebookfoo ##############", "access_token : " + accessToken); Session session = Session.getActiveSession(); AccessToken currentToken = session.getTokenInfo(); /*[NJ] Need to use the page access token in the session, with a couple of changes in the facebook sdk 1. make setTokenInfo public 2. Make AccessToken pubic */ session.setTokenInfo(new AccessToken(accessToken, currentToken.getExpires(), currentToken.getPermissions(), currentToken.getDeclinedPermissions(), currentToken.getSource(), currentToken.getLastRefresh())); } } } catch (Exception e) { } } else { Log.d("facebookfoo ###############", "retrievig user pages fail"); } }
From source file:com.microsoft.sharepointservices.ListClient.java
/** * Gets columns from default view.//from w ww . j av a 2 s. c o m * * @param listName the list name * @return the columns from default view */ public ListenableFuture<List<String>> getColumnsFromDefaultView(final String listName) { final SettableFuture<List<String>> result = SettableFuture.create(); String getViewUrl = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/defaultView/viewfields", urlEncode(listName)); ListenableFuture<JSONObject> request = executeRequestJson(getViewUrl, "GET"); Futures.addCallback(request, new FutureCallback<JSONObject>() { @Override public void onFailure(Throwable t) { result.setException(t); } @Override public void onSuccess(JSONObject json) { try { JSONObject container = json.getJSONObject("d"); JSONArray results = container.getJSONObject("Items").getJSONArray("results"); ArrayList<String> columnNames = new ArrayList<String>(); for (int i = 0; i < results.length(); i++) { columnNames.add(results.get(i).toString()); } result.set(columnNames); } catch (JSONException e) { log(e); } } }); return result; }
From source file:com.watabou.pixeldungeon.utils.Bundle.java
public int[] getIntArray(String key) { try {/*w ww . j a v a 2s.co m*/ JSONArray array = data.getJSONArray(key); int length = array.length(); int[] result = new int[length]; for (int i = 0; i < length; i++) { result[i] = array.getInt(i); } return result; } catch (JSONException e) { return null; } }