List of usage examples for org.json JSONArray get
public Object get(int index) throws JSONException
From source file:com.hichinaschool.flashcards.libanki.Models.java
/** * Removing a template// www . j ava 2 s.c om * * @return False if removing template would leave orphan notes. */ public boolean remTemplate(JSONObject m, JSONObject template) { try { assert (m.getJSONArray("tmpls").length() > 1); // find cards using this template JSONArray ja = m.getJSONArray("tmpls"); int ord = -1; for (int i = 0; i < ja.length(); ++i) { if (ja.get(i).equals(template)) { ord = i; break; } } String sql = "select c.id from cards c, notes f where c.nid=f.id and mid = " + m.getLong("id") + " and ord = " + ord; long[] cids = Utils.toPrimitive(mCol.getDb().queryColumn(Long.class, sql, 0)); // all notes with this template must have at least two cards, or we could end up creating orphaned notes sql = "select nid, count() from cards where nid in (select nid from cards where id in " + Utils.ids2str(cids) + ") group by nid having count() < 2 limit 1"; if (mCol.getDb().queryScalar(sql, false) != 0) { return false; } // ok to proceed; remove cards mCol.modSchema(); mCol.remCards(cids); // shift ordinals mCol.getDb().execute( "update cards set ord = ord - 1, usn = ?, mod = ? where nid in (select id from notes where mid = ?) and ord > ?", new Object[] { mCol.usn(), Utils.intNow(), m.getLong("id"), ord }); JSONArray tmpls = m.getJSONArray("tmpls"); JSONArray ja2 = new JSONArray(); for (int i = 0; i < tmpls.length(); ++i) { if (template.equals(tmpls.getJSONObject(i))) { continue; } ja2.put(tmpls.get(i)); } m.put("tmpls", ja2); } catch (JSONException e) { throw new RuntimeException(e); } _updateTemplOrds(m); save(m); return true; }
From source file:com.hichinaschool.flashcards.libanki.Models.java
public void moveTemplate(JSONObject m, JSONObject template, int idx) { try {// ww w. j a va2s. c om JSONArray ja = m.getJSONArray("tmpls"); int oldidx = -1; ArrayList<JSONObject> l = new ArrayList<JSONObject>(); HashMap<Integer, Integer> oldidxs = new HashMap<Integer, Integer>(); for (int i = 0; i < ja.length(); ++i) { if (ja.get(i).equals(template)) { oldidx = i; if (idx == oldidx) { return; } } JSONObject t = ja.getJSONObject(i); oldidxs.put(t.hashCode(), t.getInt("ord")); l.add(t); } l.remove(oldidx); l.add(idx, template); m.put("tmpls", new JSONArray(l)); _updateTemplOrds(m); // generate change map - We use StringBuilder StringBuilder sb = new StringBuilder(); ja = m.getJSONArray("tmpls"); for (int i = 0; i < ja.length(); ++i) { JSONObject t = ja.getJSONObject(i); sb.append("when ord = ").append(oldidxs.get(t.hashCode())).append(" then ").append(t.getInt("ord")); if (i != ja.length() - 1) { sb.append(" "); } } // apply save(m); mCol.getDb().execute( "update cards set ord = (case " + sb.toString() + " end),usn=?,mod=? where nid in (select id from notes where mid = ?)", new Object[] { mCol.usn(), Utils.intNow(), m.getLong("id") }); } catch (JSONException e) { throw new RuntimeException(e); } }
From source file:com.reignite.parser.QueryParser.java
private Object createArray(JSONArray jarr) throws JSONException, ParserException { Object[] arr = new Object[jarr.length()]; for (int i = 0; i < jarr.length(); i++) { arr[i] = createValue(jarr.get(i)); }/*from w w w . ja v a 2s. c om*/ return arr; }
From source file:com.reignite.parser.QueryParser.java
private void addFields(JSONObject jobj) throws ParserException { if (jobj.has("fields")) { JSONArray fields; try {/*w w w . java2s . c om*/ fields = jobj.getJSONArray("fields"); } catch (JSONException e) { throw new ParserException("fields must be a JSONArray containing either strings or JSONObjects"); } for (int i = 0; i < fields.length(); i++) { Object field; try { field = fields.get(i); } catch (JSONException e) { throw new ParserException("fields must not be an empty JSONArray if it is included."); } if (field instanceof String) { query.addField(field.toString()); } else if (field instanceof JSONObject) { JSONObject jField = (JSONObject) field; String[] names = JSONObject.getNames(jField); for (String aggType : names) { QueryType type = QueryType.valueOf(aggType.toUpperCase()); try { // query.addField(jField.getString(aggType)); query.addAggregate(type, jField.getString(aggType)); } catch (JSONException e) { throw new ParserException( "aggregate fields must be of the form {sum|avg|count:'field'}"); } } } } } }
From source file:jessmchung.groupon.parsers.GrouponTypeParser.java
public Collection<T> parse(JSONArray array) throws JSONException { Collection<T> collection = new ArrayList<T>(); for (int i = 0, m = array.length(); i < m; i++) { Object element = array.get(i); T item = null;// w ww .j a va 2 s . c om if (element instanceof JSONArray) { //item = parse((JSONArray)element); } else { item = parse((JSONObject) element); } collection.add(item); } return collection; }
From source file:com.projectgoth.mywebrtcdemo.ConnectActivity.java
@Override public void onResume() { super.onResume(); String room = sharedPref.getString(keyprefRoom, ""); roomEditText.setText(room);/* w ww .j a va 2s .c o m*/ roomList = new ArrayList<String>(); String roomListJson = sharedPref.getString(keyprefRoomList, null); if (roomListJson != null) { try { JSONArray jsonArray = new JSONArray(roomListJson); for (int i = 0; i < jsonArray.length(); i++) { roomList.add(jsonArray.get(i).toString()); } } catch (JSONException e) { Log.e(TAG, "Failed to load room list: " + e.toString()); } } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, roomList); roomListView.setAdapter(adapter); if (adapter.getCount() > 0) { roomListView.requestFocus(); roomListView.setItemChecked(0, true); } }
From source file:uk.ac.imperial.presage2.web.SimDataServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logRequest(req);//from w w w .ja va 2 s .c om // find simid parameter long simId = 0; if (req.getParameter("filter") != null) { // extjs param try { JSONArray filter = new JSONArray(req.getParameter("filter")); JSONObject first = (JSONObject) filter.get(0); if (first.getString("property").equals("presage2.model.simulation_id")) { simId = first.getInt("value"); } else { resp.setStatus(400); return; } } catch (JSONException e) { resp.setStatus(400); return; } } else if (req.getParameter("id") != null) { simId = Long.parseLong(req.getParameter("id").toString()); } else { resp.setStatus(400); return; } if (simId > 0) { // list transient data for simulation specified final int start = getIntegerParameter(req, "start", 0); final int limit = getIntegerParameter(req, "limit", 25); // get simulation PersistentSimulation sim = sto.getSimulationById(simId); if (sim == null) { resp.setStatus(401); return; } try { JSONObject responseJson = new JSONObject(); responseJson.put("simId", simId); // get number of data points responseJson.put("totalCount", sim.getCurrentTime()); JSONArray datapoints = new JSONArray(); if (sim.getCurrentTime() > start) { int current = start; while (current < start + limit && current < sim.getCurrentTime()) { JSONObject point = new JSONObject(); point.put("time", current); for (Map.Entry<String, String> entry : sim.getEnvironment().getProperties().entrySet()) { point.put(entry.getKey(), entry.getValue()); } JSONArray agents = new JSONArray(); for (PersistentAgent agent : sim.getAgents()) { JSONObject agentJson = new JSONObject(); agentJson.put("aid", agent.getID()); agentJson.put("data", agent.getState(current).getProperties()); agents.put(agentJson); } point.put("agents", agents); datapoints.put(point); current++; } } responseJson.put("data", datapoints); responseJson.put("success", true); resp.setStatus(200); resp.getWriter().write(responseJson.toString()); } catch (JSONException e) { resp.setStatus(500); } } else { resp.setStatus(400); } }
From source file:io.spring.initializr.actuate.stat.MainControllerStatsIntegrationTests.java
@Test public void simpleProject() { downloadArchive("/starter.zip?groupId=com.foo&artifactId=bar&dependencies=web"); assertEquals("No stat got generated", 1, statsMockController.stats.size()); StatsMockController.Content content = statsMockController.stats.get(0); JSONObject json = new JSONObject(content.json); assertEquals("com.foo", json.get("groupId")); assertEquals("bar", json.get("artifactId")); JSONArray list = json.getJSONArray("dependencies"); assertEquals(1, list.length());// w w w .j a v a 2 s . c o m assertEquals("web", list.get(0)); }
From source file:it.sardegnaricerche.voiceid.sr.Voiceid.java
public JSONObject toJson() throws JSONException, UnsupportedAudioFileException, IOException, LineUnavailableException { JSONObject obj = new JSONObject(); JSONArray arr_tmp = new JSONArray(); try {/* ww w.jav a 2 s . c o m*/ obj.put("duration", new WavSample(this.wavPath).getDuration()); } catch (Exception e) { double best = 0.0; for (VCluster c : this.clusters) for (VSegment s : c.getSegments()) { double curr = s.getEnd(); if (curr > best) best = curr; } obj.put("duration", best); } obj.put("url", this.inputfile.getAbsolutePath()); for (VCluster c : this.clusters) { JSONArray jsa = c.toJson(); for (int i = 0; i < jsa.length(); i++) { arr_tmp.put(jsa.get(i)); } } obj.put("selections", arr_tmp); return obj; }
From source file:com.smedic.tubtub.JsonAsyncTask.java
@Override protected ArrayList<String> doInBackground(String... params) { //encode param to avoid spaces in URL String encodedParam = ""; try {/*from w w w. j ava 2s.com*/ encodedParam = URLEncoder.encode(params[0], "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ArrayList<String> items = new ArrayList<>(); try { URL url = new URL( "http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=" + encodedParam); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // gets the server json data BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String next; while ((next = bufferedReader.readLine()) != null) { if (checkJson(next) == JSON_ERROR) { //if not valid, remove invalid parts (this is simple hack for URL above) next = next.substring(19, next.length() - 1); } JSONArray ja = new JSONArray(next); for (int i = 0; i < ja.length(); i++) { if (ja.get(i) instanceof JSONArray) { JSONArray ja2 = ja.getJSONArray(i); for (int j = 0; j < ja2.length(); j++) { if (ja2.get(j) instanceof JSONArray) { String suggestion = ((JSONArray) ja2.get(j)).getString(0); //Log.d(TAG, "Suggestion: " + suggestion); items.add(suggestion); } } } else if (ja.get(i) instanceof JSONObject) { //Log.d(TAG, "json object"); } else { //Log.d(TAG, "unknown object"); } } } } catch (IOException | JSONException e) { e.printStackTrace(); } return items; }