List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:ai.susi.mind.SusiSkill.java
/** * Create a skill by parsing of the skill description * @param json the skill description//from w ww. j a v a2 s.c o m * @throws PatternSyntaxException */ private SusiSkill(JSONObject json) throws PatternSyntaxException { // extract the phrases and the phrases subscore if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); JSONArray p = (JSONArray) json.remove("phrases"); this.phrases = new ArrayList<>(p.length()); p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q))); // extract the actions and the action subscore if (!json.has("actions")) throw new PatternSyntaxException("actions missing", "", 0); p = (JSONArray) json.remove("actions"); this.actions = new ArrayList<>(p.length()); p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q))); // extract the inferences and the process subscore; there may be no inference at all if (json.has("process")) { p = (JSONArray) json.remove("process"); this.inferences = new ArrayList<>(p.length()); p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q))); } else { this.inferences = new ArrayList<>(0); } // extract (or compute) the keys; there may be none key given, then they will be computed this.keys = new HashSet<>(); JSONArray k; if (json.has("keys")) { k = json.getJSONArray("keys"); if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0)) k = computeKeysFromPhrases(this.phrases); } else { k = computeKeysFromPhrases(this.phrases); } k.forEach(o -> this.keys.add((String) o)); this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE; this.score = null; // calculate this later if required // extract the comment this.comment = json.has("comment") ? json.getString("comment") : ""; // calculate the id String ids0 = this.actions.toString(); String ids1 = this.phrases.toString(); this.id = ids0.hashCode() + ids1.hashCode(); }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static JSONArray addRepeatedNodeToJson(Element container, Repeat f, String permlevel, JSONObject tempSon) throws JSONException { JSONArray node = new JSONArray(); List<FieldSet> children = getChildrenWithGroupFields(f, permlevel); JSONArray elementlist = extractRepeatData(container, f, permlevel); JSONObject siblingitem = new JSONObject(); for (int i = 0; i < elementlist.length(); i++) { JSONObject element = elementlist.getJSONObject(i); Iterator<?> rit = element.keys(); while (rit.hasNext()) { String key = (String) rit.next(); JSONArray arrvalue = new JSONArray(); for (FieldSet fs : children) { if (fs instanceof Repeat && ((Repeat) fs).hasServicesParent()) { if (!((Repeat) fs).getServicesParent()[0].equals(key)) { continue; }/*from w w w . j ava 2 s. c om*/ Object value = element.get(key); arrvalue = (JSONArray) value; } else { if (!fs.getID().equals(key)) { continue; } Object value = element.get(key); arrvalue = (JSONArray) value; } if (fs instanceof Field) { for (int j = 0; j < arrvalue.length(); j++) { JSONObject repeatitem = new JSONObject(); //XXX remove when service layer supports primary tags if (f.hasPrimary() && j == 0) { repeatitem.put("_primary", true); } Element child = (Element) arrvalue.get(j); Object val = child.getText(); Field field = (Field) fs; String id = field.getID(); if (f.asSibling()) { addExtraToJson(siblingitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { siblingitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { siblingitem.put(id, val); } } else { addExtraToJson(repeatitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { repeatitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { repeatitem.put(id, val); } node.put(repeatitem); } tempSon = addtemp(tempSon, fs.getID(), child.getText()); } } else if (fs instanceof Group) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Group rp = (Group) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { JSONArray a1 = tout.getJSONArray(rp.getID()); JSONObject o1 = a1.getJSONObject(0); siblingitem.put(fs.getID(), o1); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } else if (fs instanceof Repeat) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Repeat rp = (Repeat) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID())); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } } } } if (f.asSibling()) { node.put(siblingitem); } return node; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addRepeatToJson(JSONObject out, Element root, Repeat f, String permlevel, JSONObject tempSon, String csid, String ims_url) throws JSONException { if (f.getXxxServicesNoRepeat()) { //not a repeat in services yet but is a repeat in UI FieldSet[] fields = f.getChildren(permlevel); if (fields.length == 0) return; JSONArray members = new JSONArray(); JSONObject data = new JSONObject(); addFieldSetToJson(data, root, fields[0], permlevel, tempSon, csid, ims_url); members.put(data);/*from w ww . jav a 2 s .co m*/ out.put(f.getID(), members); return; } String nodeName = f.getServicesTag(); if (f.hasServicesParent()) { nodeName = f.getfullID(); //XXX hack because of weird repeats in accountroles permroles etc if (f.getServicesParent().length == 0) { nodeName = f.getID(); } } List<?> nodes = root.selectNodes(nodeName); if (nodes.size() == 0) {// add in empty primary tags and arrays etc to help UI if (f.asSibling()) { JSONObject repeated = new JSONObject(); if (f.hasPrimary()) { repeated.put("_primary", true); } if (!out.has(f.getID())) { JSONArray temp = new JSONArray(); out.put(f.getID(), temp); } out.getJSONArray(f.getID()).put(repeated); } else { JSONArray repeatitem = new JSONArray(); out.put(f.getID(), repeatitem); } return; } // Only first element is important in container //except when we have repeating items int pos = 0; for (Object repeatcontainer : nodes) { pos++; Element container = (Element) repeatcontainer; if (f.asSibling()) { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); JSONArray temp = new JSONArray(); if (!out.has(f.getID())) { out.put(f.getID(), temp); } for (int arraysize = 0; arraysize < repeatitem.length(); arraysize++) { JSONObject repeated = repeatitem.getJSONObject(arraysize); if (f.hasPrimary() && pos == 1) { repeated.put("_primary", true); } out.getJSONArray(f.getID()).put(repeated); } } else { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); out.put(f.getID(), repeatitem); } } }
From source file:com.rsimiao.exemplosloopj.UsuarioWS.java
public void buscar(final Handler handler) { try {/*from w w w .ja v a 2 s . co m*/ RequestParams parametros = new RequestParams(); parametros.add("limite", "todos"); Wscliente.post(url, parametros, new AsyncHttpResponseHandler() { @Override public void onFailure(int code, Header[] header, byte[] conteudo, Throwable arg3) { //voc pode colocar aqui seu tratamento de erro Log.d("WS USUARIO", "DEU ERRO"); Message msg = new Message(); msg.what = 0; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro. handler.sendMessage(msg); } @Override public void onSuccess(int code, Header[] header, byte[] conteudo) { try { JSONObject json = new JSONObject(new String(conteudo)); List<Usuario> usuarios = new ArrayList<Usuario>(); //sua lgica para tratar o json recebido (no precisa ser desse modo jurstico) if (json.has("status") && json.getString("status").equalsIgnoreCase("success")) { JSONArray jUsrs = json.getJSONArray("usuarios"); for (int i = 0; i < jUsrs.length(); i++) { Usuario u = new Usuario(); u.setNome(jUsrs.getJSONObject(i).getString("nome")); u.setUsuario(jUsrs.getJSONObject(i).getString("usuario")); u.setLogged(jUsrs.getJSONObject(i).getBoolean("islogged")); usuarios.add(u); } Message msg = new Message(); msg.what = 1; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro. msg.obj = usuarios; handler.sendMessage(msg); } } catch (JSONException e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.markupartist.sthlmtraveling.provider.planner.JourneyQuery.java
public static JourneyQuery fromJson(JSONObject jsonObject) throws JSONException { JourneyQuery journeyQuery = new JourneyQuery.Builder().origin(jsonObject.getJSONObject("origin")) .destination(jsonObject.getJSONObject("destination")) .transportModes(jsonObject.has("transportModes") ? jsonObject.getJSONArray("transportModes") : null) .create();/*from ww w . j av a 2 s .c om*/ if (jsonObject.has("isTimeDeparture")) { journeyQuery.isTimeDeparture = jsonObject.getBoolean("isTimeDeparture"); } if (jsonObject.has("alternativeStops")) { journeyQuery.alternativeStops = jsonObject.getBoolean("alternativeStops"); } if (jsonObject.has("via")) { JSONObject jsonVia = jsonObject.getJSONObject("via"); Location via = new Location(); via.name = jsonVia.getString("name"); journeyQuery.via = via; } return journeyQuery; }
From source file:drusy.ui.panels.WifiStatePanel.java
public void update(final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_WIFI_ID, output, "Getting WiFi id", false); task.addListener(new HttpUtils.DownloadListener() { @Override//from w w w .j av a2 s . co m public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); if (success == true) { JSONArray result = obj.getJSONArray("result"); JSONObject wifi = result.getJSONObject(0); int id = wifi.getInt("id"); addUsersForWifiId(id, updater); } else { String msg = obj.getString("msg"); Log.Debug("Freebox Wi-Fi State (get id)", msg); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Wi-Fi State (get id)", ex.getMessage()); } }); }
From source file:drusy.ui.panels.WifiStatePanel.java
public void addUsersForWifiId(int id, final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); String statement = Config.FREEBOX_API_WIFI_STATIONS.replace("{id}", String.valueOf(id)); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting WiFi id", false); task.addListener(new HttpUtils.DownloadListener() { @Override/*from w ww . j av a 2 s. co m*/ public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); clearUsers(); if (success == true) { final JSONArray usersList = obj.getJSONArray("result"); for (int i = 0; i < usersList.length(); ++i) { JSONObject user = usersList.getJSONObject(i); final String hostname = user.getString("hostname"); final long txBytes = user.getLong("tx_rate"); final long rxBytes = user.getLong("rx_rate"); JSONObject host = user.getJSONObject("host"); final String host_type = host.getString("host_type"); addUser(host_type, hostname, txBytes, rxBytes); } } else { String msg = obj.getString("msg"); Log.Debug("Freebox Wi-Fi State (get users)", msg); } if (updater != null) { updater.updated(); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Wi-Fi State (get users)", ex.getMessage()); if (updater != null) { updater.updated(); } } }); }
From source file:org.everit.json.schema.IssueTest.java
private void readExpectedValues(final JSONObject expected) { expectedFailureList.add((String) expected.get("message")); if (expected.has("causingExceptions")) { JSONArray causingEx = expected.getJSONArray("causingExceptions"); for (Object subJson : causingEx) { readExpectedValues((JSONObject) subJson); }/*from w w w.j a v a 2 s . c o m*/ } }
From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java
public static void saveBookNames(SQLiteDatabase db, JSONObject booksInfoObject) throws Exception { final String translationShortName = booksInfoObject.getString("shortName"); final ContentValues bookNamesValues = new ContentValues(3); bookNamesValues.put(DatabaseHelper.COLUMN_TRANSLATION_SHORT_NAME, translationShortName); final JSONArray booksArray = booksInfoObject.getJSONArray("books"); for (int i = 0; i < Bible.getBookCount(); ++i) { bookNamesValues.put(DatabaseHelper.COLUMN_BOOK_INDEX, i); final String bookName = booksArray.getString(i); if (TextUtils.isEmpty(bookName)) throw new Exception("Illegal books.json file: " + translationShortName); bookNamesValues.put(DatabaseHelper.COLUMN_BOOK_NAME, bookName); db.insert(DatabaseHelper.TABLE_BOOK_NAMES, null, bookNamesValues); }//from w ww.j av a 2 s. co m }
From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java
public static void saveVerses(SQLiteDatabase db, String translationShortName, int bookIndex, int chapterIndex, JSONObject versesObject) throws Exception { final ContentValues versesValues = new ContentValues(4); versesValues.put(DatabaseHelper.COLUMN_BOOK_INDEX, bookIndex); versesValues.put(DatabaseHelper.COLUMN_CHAPTER_INDEX, chapterIndex); final JSONArray paragraphArray = versesObject.getJSONArray("verses"); final int paragraphCount = paragraphArray.length(); boolean hasNonEmptyVerse = false; for (int verseIndex = 0; verseIndex < paragraphCount; ++verseIndex) { versesValues.put(DatabaseHelper.COLUMN_VERSE_INDEX, verseIndex); final String verse = paragraphArray.getString(verseIndex); if (!hasNonEmptyVerse && !TextUtils.isEmpty(verse)) hasNonEmptyVerse = true;/* w w w . jav a2 s . c om*/ versesValues.put(DatabaseHelper.COLUMN_TEXT, verse); db.insert(translationShortName, null, versesValues); } if (!hasNonEmptyVerse) { throw new Exception( String.format("Empty chapter: %s %d-%d", translationShortName, bookIndex, chapterIndex)); } }