List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java
public List<String> getList(JSONObject server, String key) { List<String> value = new ArrayList<>(); for (int i = 0; i < server.getJSONArray(key).length(); i++) { value.add(server.getJSONArray(key).getString(i)); }/*from w w w. j a va 2s.c o m*/ return value; }
From source file:com.appdynamics.demo.gasp.fragment.TwitterResponderFragment.java
private static List<String> getTweetsFromJson(String json) { ArrayList<String> tweetList = new ArrayList<String>(); try {/* ww w . j av a 2 s . c o m*/ 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();/*from w w w . j a v a 2s . c o m*/ 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. * /* w w w. j av a2 s. c om*/ * 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;/*from w w w .ja v a2s .c o m*/ 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;// w w w. j a v a 2 s . co m JSONObject obj; 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
/** * get paginated list of results//from w w w . j a v a 2 s . c o m * * @param user * @param feedName * @param <T> * @return * @throws Exception */ private <T> LinkedList<T> getResultList(String user, String feedName) throws Exception { LinkedList<T> results = new LinkedList<T>(); String query = GRAPH_API_HOST + user + "/" + feedName; boolean hasMore = true; while (hasMore == true) { JSONObject response = getResponse(query); JSONArray resultArray = response.getJSONArray("data"); loadResults(results, resultArray, feedName); if (hasMore(response)) { String nextQuery = getNextPageURL(response); if (!nextQuery.equals(query)) { query = nextQuery; } else { hasMore = false; } } else { hasMore = false; } } return results; }
From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java
/** * get "data" entry fron JSON response/*from ww w . ja va2 s . c om*/ * * @param query * @return * @throws Exception */ private JSONArray getDataArray(String query) throws Exception { JSONObject response = getResponse(query); return response.getJSONArray("data"); }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
public ICalTask(ActionManager actionManager, String providerId, JSONObject json) { this.actionManager = actionManager; this.providerId = providerId; this.event = new VEvent(); String id;//from w w w . j a v a2 s . c o m if (json.has("id")) { id = json.getString("id"); } else { id = UUID.randomUUID().toString(); } event.getProperties().add(new Uid(id)); event.getProperties().add(new Summary(json.getString("name"))); try { if (json.has("conditions")) { JSONArray conditions = json.getJSONArray("conditions"); if (conditions.length() == 1) { JSONObject jc = conditions.getJSONObject(0); if (jc.has("start") && !jc.isNull("start")) { event.getProperties().add(new DtStart(jc.getString("start"))); } if (jc.has("recurrence") && !jc.isNull("recurrence")) { event.getProperties().add(new RRule(jc.getString("recurrence"))); } if (jc.has("sunOffset") && !jc.isNull("sunOffset")) { event.getProperties().add(new XProperty(PROP_SUN_OFFSET, jc.getString("sunOffset"))); } } else { throw new HobsonRuntimeException("ICalTasks only support one condition"); } } } catch (ParseException e) { throw new HobsonRuntimeException("Error parsing recurrence rule", e); } try { if (json.has("actions")) { JSONArray actions = json.getJSONArray("actions"); event.getProperties().add(new Comment(actions.toString())); for (int i = 0; i < actions.length(); i++) { addActionRef(actions.getJSONObject(i)); } } } catch (Exception e) { throw new HobsonRuntimeException("Error parsing actions", e); } }
From source file:ai.susi.mind.SusiSkill.java
/** * Generate a set of skills from a single skill definition. This may be possible if the skill contains an 'options' * object which creates a set of skills, one for each option. The options combine with one set of phrases * @param json - a multi-skill definition * @return a set of skills// ww w . j a v a 2s. c om */ public static List<SusiSkill> getSkills(JSONObject json) { if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); final List<SusiSkill> skills = new ArrayList<>(); if (json.has("options")) { JSONArray options = json.getJSONArray("options"); for (int i = 0; i < options.length(); i++) { JSONObject option = new JSONObject(); option.put("phrases", json.get("phrases")); JSONObject or = options.getJSONObject(i); for (String k : or.keySet()) option.put(k, or.get(k)); skills.add(new SusiSkill(option)); } } else { try { SusiSkill skill = new SusiSkill(json); skills.add(skill); } catch (PatternSyntaxException e) { Logger.getLogger("SusiSkill") .warning("Regular Expression error in Susi Skill: " + json.toString(2)); } } return skills; }