List of usage examples for org.json JSONArray JSONArray
public JSONArray()
From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java
private JSONArray adjustTimeAndTipiSpecifici(String dataAsCSV) throws ParseException { JSONArray jsonArray = CDL.toJSONArray(dataAsCSV); int length = jsonArray.length(); JSONArray jsonArrayNew = new JSONArray(); for (int i = 0; i < length; i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); JSONObject jsonObjectNew = new JSONObject(); jsonObjectNew.put("nome", jsonObject.getString("nome")); jsonObjectNew.put("indirizzo", jsonObject.getString("indirizzo")); jsonObjectNew.put("numeroCivico", jsonObject.getString("numero-civico")); jsonObjectNew.put("cap", jsonObject.getString("cap")); jsonObjectNew.put("quartiere", jsonObject.getString("quartiere")); jsonObjectNew.put("citta", jsonObject.getString("citta")); jsonObjectNew.put("geolocazione", jsonObject.getString("geolocazione")); jsonObjectNew.put("telefono", jsonObject.getString("telefono")); jsonObjectNew.put("mobile", jsonObject.getString("mobile")); jsonObjectNew.put("email", jsonObject.getString("email")); jsonObjectNew.put("web", jsonObject.getString("web")); jsonObjectNew.put("tipi", jsonObject.getString("tipi")); jsonObjectNew.put("tipiSpecifici", jsonObject.getString("tipi-specifici")); // jsonObjectNew.put("tipiSpecificiReduced", getTipiReduced(jsonObject)); // jsonObjectNew.put("times", getTimes(jsonObject)); LinkedList<String> date = findNumbers(jsonObject.getString("luogo-da-visitare.informazioni_storiche")); String dateString = date.toString().replace("[", "").replace("]", ""); jsonObjectNew.put("luoghiDaVisitare.informazioniStoriche.date", dateString); jsonArrayNew.put(jsonObjectNew); }//w w w . j av a 2 s. c o m return jsonArrayNew; }
From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java
private JSONArray getTimes(JSONObject jsonObject) throws ParseException { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = "1970-01-01"; JSONArray times = new JSONArray(); String apertura = jsonObject.getString("apertura"); long startingTimeEpoch = 0; if (apertura.isEmpty()) apertura = "19.00"; // default startingTimeEpoch = sdf.parse(date + " " + apertura.replace(".", ":")).getTime(); String chiusura = jsonObject.getString("chiusura"); long endingTimeEpoch = 0; if (chiusura.isEmpty()) chiusura = "1.00"; // default double parsedEndingTime = Double.parseDouble(chiusura); if (parsedEndingTime >= 0f && parsedEndingTime < 6f) // we are in next day date = "1970-01-02"; endingTimeEpoch = sdf.parse(date + " " + chiusura.replace(".", ":")).getTime(); String startingTimeEpoched = "" + startingTimeEpoch; String endingTimeEpoched = "" + endingTimeEpoch; JSONObject et = new JSONObject(); et.put("starting_time", startingTimeEpoched); et.put("ending_time", endingTimeEpoched); times.put(et);/* w w w. j av a 2 s . com*/ return times; }
From source file:com.util.httpAccount.java
public Account getAccountObject(String tel) { String telefono = tel.replace("-", ""); System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;//from w w w . j a va2s .c o m Account account = new Account(); try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); 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(); } } String jsonResult = sb.toString(); // System.out.println(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"); //System.out.println("objeto normal 1 "+dataJson.toString()); // // // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); // System.out.println("new json string"+jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); // System.out.println("el objeto simple json es " + objJson2.toString()); // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); // System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); // System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); // System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("language_id")); // System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); account = gson.fromJson(objJson3.toString(), Account.class); //System.out.println(account.getFirst_name()); // System.out.println(account.getCreation()); account.setLanguaje_id(objJson3.get("language_id").toString()); account.setId(objJson3.get("id").toString()); account.setBalance(objJson3.get("balance").toString()); System.out.println("el id del account es " + account.getId()); } else { System.out.print("no se pudo conectar con el servidor"); account = null; } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } return account; }
From source file:com.handshake.notifications.MyGcmListenerService.java
/** * Called when message is received./* w w w. j a v a 2 s. c om*/ * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, final Bundle data) { SessionManager session = new SessionManager(this); if (!session.isLoggedIn()) return; /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ try { final JSONArray users = new JSONArray(); if (!data.containsKey("user")) return; final JSONObject user = new JSONObject(data.getString("user")); users.put(user); UserServerSync.cacheUser(getApplicationContext(), users, new UserArraySyncCompleted() { @Override public void syncCompletedListener(final ArrayList<User> users) { if (users.size() == 0) { sendNotification(data, 0, false); return; } final long userId = users.get(0).getUserId(); final boolean isContact = users.get(0).isContact(); FeedItemServerSync.performSync(getApplicationContext(), new SyncCompleted() { @Override public void syncCompletedListener() { ContactSync.performSync(getApplicationContext(), new SyncCompleted() { @Override public void syncCompletedListener() { if (data.containsKey("group_id")) { Realm realm = Realm.getInstance(getApplicationContext()); Group group = realm.where(Group.class) .equalTo("groupId", Long.parseLong(data.getString("group_id"))) .findFirst(); GroupServerSync.loadGroupMembers(group); realm.close(); } sendNotification(data, userId, isContact); } }); } }); } }); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.soomla.store.domain.VirtualCategory.java
/** * Converts the current {@link VirtualCategory} to a JSONObject. * @return a JSONObject representation of the current {@link VirtualCategory}. *///w ww .j av a 2 s . c o m public JSONObject toJSONObject() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(JSONConsts.CATEGORY_NAME, mName); JSONArray goodsArr = new JSONArray(); for (String goodItemId : mGoodsItemIds) { goodsArr.put(goodItemId); } jsonObject.put(JSONConsts.CATEGORY_GOODSITEMIDS, goodsArr); } catch (JSONException e) { StoreUtils.LogError(TAG, "An error occurred while generating JSON object."); } return jsonObject; }
From source file:IoTatWork.AuCapTreeResource.java
/** * //from w w w.j ava2 s . co m * @param auCapRid * @param depth * @param jsonNodeTree * @return */ private void getJsonNodeTree(Vertex auCapNode, JSONObject jsonNodeTree, int depth, boolean toRevoke, Object revokedSince) { //graph.getRawGraph(); try { OGraphDatabase rawGraph = graph.getRawGraph(); ODocument doc = rawGraph.load((ORID) auCapNode.getId()); //System.out.println(doc.getClassName()); if (doc.getClassName().equals(DataMapper.AUCAP_VERTEX)) { getJsonAuCapVertexData(auCapNode, jsonNodeTree); JSONObject jsonData = (JSONObject) jsonNodeTree.get("data"); if (!toRevoke) { //controllo se lui o i figli sono sa revocare String status = (String) auCapNode.getProperty(DataMapper.STATUS); if (status.equals(Status.REVOKED)) { String revocationScope = (String) auCapNode.getProperty(DataMapper.REVOCATION_SCOPE); if (revocationScope.equals(RevocationScope.ALL)) { jsonData.put(DataMapper.STATUS, Status.REVOKED); jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE)); toRevoke = true; revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE); } else if (revocationScope.equals(RevocationScope.THIS)) { jsonData.put(DataMapper.STATUS, Status.REVOKED); jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE)); } else if (revocationScope.equals(RevocationScope.DESCENDANT)) { jsonData.put(DataMapper.STATUS, Status.VALID); toRevoke = true; revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE); } } } else { //metto lo status a Revoked e metto il campo revokedSince jsonData.put(DataMapper.REVOKED_SINCE, revokedSince); jsonData.put(DataMapper.STATUS, Status.REVOKED); } Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT, DataMapper.DEPENDENT_CAPABILIES_LABEL); JSONArray jsonArrayDependant = new JSONArray(); depth++; for (Edge depend : dependentEdges) { if (depth <= this.depth) { JSONObject jsonDependantNode = new JSONObject(); jsonArrayDependant.put(jsonDependantNode); Vertex dependantVertex = depend.getVertex(Direction.IN); getJsonNodeTree(dependantVertex, jsonDependantNode, depth, toRevoke, revokedSince); } } jsonNodeTree.put("children", jsonArrayDependant); } else { jsonNodeTree.put("id", auCapNode.getId().toString().substring(1)); jsonNodeTree.put("name", auCapNode.getProperty("name").toString()); Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT); JSONObject jsonData = new JSONObject(); String edgeLabel = dependentEdges.iterator().next().getLabel(); jsonData.put("edgeLabel", edgeLabel); jsonNodeTree.put("data", jsonData); JSONArray jsonArrayDependant = new JSONArray(); depth++; for (Edge depend : dependentEdges) { if (depth <= this.depth) { JSONObject jsonDependantNode = new JSONObject(); jsonArrayDependant.put(jsonDependantNode); Vertex dependantVertex = depend.getVertex(Direction.IN); getJsonNodeTree(dependantVertex, jsonDependantNode, depth, false, null); } } jsonNodeTree.put("children", jsonArrayDependant); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:IoTatWork.AuCapTreeResource.java
/** * //ww w .ja v a 2 s .co m * @param auCapNode * @param jsonNodeTree * @return */ private void getJsonAuCapVertexData(Vertex auCapNode, JSONObject jsonNodeTree) { try { Vertex detailsVertex = auCapNode.getEdges(Direction.OUT, DataMapper.DETAILS_LABEL).iterator().next() .getVertex(Direction.IN); jsonNodeTree.put("id", auCapNode.getId().toString().substring(1)); jsonNodeTree.put("name", detailsVertex.getProperty(DataMapper.SUBJECT_ID).toString()); JSONObject jsonVertexData = new JSONObject(); jsonVertexData.put("edgeLabel", DataMapper.DEPENDENT_CAPABILIES_LABEL); //AuCapVertex jsonVertexData.put(DataMapper.CAPABILITY_ID, auCapNode.getProperty(DataMapper.CAPABILITY_ID)); jsonVertexData.put(DataMapper.CAPABILITY_ISSUER, auCapNode.getProperty(DataMapper.CAPABILITY_ISSUER)); jsonVertexData.put(DataMapper.CAPABILITY_ISSUE_TIME, auCapNode.getProperty(DataMapper.CAPABILITY_ISSUE_TIME)); String status = (String) auCapNode.getProperty(DataMapper.STATUS); jsonVertexData.put(DataMapper.STATUS, status); /* if(status.equals(Status.REVOKED)){ String revocationScope = (String) auCapNode.getProperty(DataMapper.REVOCATION_SCOPE); jsonVertexData.put(DataMapper.REVOCATION_SCOPE, revocationScope); if(revocationScope.equals(RevocationScope.ALL)){ jsonVertexData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE)); jsonVertexData.put(DataMapper.DESCENDANT_REVOKED_SINCE, auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE)); }else if(revocationScope.equals(RevocationScope.THIS)){ jsonVertexData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE)); }else if(revocationScope.equals(RevocationScope.DESCENDANT)){ jsonVertexData.put(DataMapper.DESCENDANT_REVOKED_SINCE, auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE)); } } */ jsonVertexData.put(DataMapper.VALIDITY_START_TIME, auCapNode.getProperty(DataMapper.VALIDITY_START_TIME)); jsonVertexData.put(DataMapper.VALIDITY_END_TIME, auCapNode.getProperty(DataMapper.VALIDITY_END_TIME)); //AuCapDetails jsonVertexData.put(DataMapper.SUBJECT_ID, detailsVertex.getProperty(DataMapper.SUBJECT_ID)); jsonVertexData.put(DataMapper.RESOURCE_ID, detailsVertex.getProperty(DataMapper.RESOURCE_ID)); jsonVertexData.put(DataMapper.REVOCATION_SERVICE_URLS, detailsVertex.getProperty(DataMapper.REVOCATION_SERVICE_URLS)); if (!auCapNode.getEdges(Direction.OUT, DataMapper.DEPENDENT_CAPABILIES_LABEL).iterator().hasNext()) { jsonVertexData.put("leaf", "leaf"); } // for(String prop : auCapNode.getPropertyKeys()){ // jsonVertexData.put(prop, auCapNode.getProperty(prop)); // } // for(String prop : detailsVertex.getPropertyKeys()){ // if(!prop.equals(DataMapper.CAPABILITY_TOKEN)) // jsonVertexData.put(prop, detailsVertex.getProperty(prop)); // } JSONArray jsonArrayAccessRights = new JSONArray(); for (Edge accessRightEdge : detailsVertex.getEdges(Direction.OUT, DataMapper.ACCESS_RIGHTS_LABEL)) { Vertex accesRightVertex = accessRightEdge.getVertex(Direction.IN); JSONObject jsonAccessRight = new JSONObject(); for (String prop : accesRightVertex.getPropertyKeys()) { jsonAccessRight.put(prop, accesRightVertex.getProperty(prop)); } jsonArrayAccessRights.put(jsonAccessRight); } jsonVertexData.put(DataMapper.ACCESS_RIGHTS_LABEL, jsonArrayAccessRights); jsonNodeTree.put("data", jsonVertexData); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public JSONObject getLocalJSONFromContent() { String name = getName();//from ww w . ja va 2s . co m try { if (mMetaInfo == null) { // new task created from web if (name == null) { Log.w(TAG, "the note seems to be an empty one"); return null; } JSONObject js = new JSONObject(); JSONObject note = new JSONObject(); JSONArray dataArray = new JSONArray(); JSONObject data = new JSONObject(); data.put(DataColumns.CONTENT, name); dataArray.put(data); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); js.put(GTaskStringUtils.META_HEAD_NOTE, note); return js; } else { // synced task JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { data.put(DataColumns.CONTENT, getName()); break; } } note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); return mMetaInfo; } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); return null; } }
From source file:edu.asu.msse.gnayak2.main.CollectionSkeleton.java
public String callMethod(String request) { JSONObject result = new JSONObject(); try {//from ww w. j a va2s .c o m JSONObject theCall = new JSONObject(request); System.out.println(request); String method = theCall.getString("method"); int id = theCall.getInt("id"); JSONArray params = null; if (!theCall.isNull("params")) { params = theCall.getJSONArray("params"); System.out.println(params); } result.put("id", id); result.put("jsonrpc", "2.0"); if (method.equals("resetFromJsonFile")) { mLib.resetFromJsonFile(); result.put("result", true); System.out.println("resetFromJsonCalled"); } else if (method.equals("remove")) { String sName = params.getString(0); boolean removed = mLib.remove(sName); System.out.println(sName + " deleted"); result.put("result", removed); } else if (method.equals("add")) { MovieImpl movie = new MovieImpl(params.getString(0)); boolean added = mLib.add(movie); result.put("result", added); } else if (method.equals("get")) { String sName = params.getString(0); MovieImpl movie = mLib.get(sName); result.put("result", movie.toJson()); } else if (method.equals("getNames")) { String[] names = mLib.getNames(); JSONArray resArr = new JSONArray(); for (int i = 0; i < names.length; i++) { resArr.put(names[i]); } result.put("result", resArr); } else if (method.equals("saveToJsonFile")) { boolean saved = mLib.saveToJsonFile(); result.put("result", saved); } else if (method.equals("getModelInformation")) { //mLib.resetFromJsonFile(); result.put("result", mLib.getModelInformation()); } else if (method.equals("update")) { String movieJSONString = params.getString(0); Movie mo = new MovieImpl(movieJSONString); mLib.updateMovie(mo); } else if (method.equals("deleteAndAdd")) { String oldMovieJSONString = params.getString(0); String editedMovieJSONString = params.getString(1); boolean deletionSuccessful = false; boolean additionSuccessful = false; MovieImpl oldMovie = new MovieImpl(oldMovieJSONString); MovieImpl newMovie = new MovieImpl(editedMovieJSONString); deletionSuccessful = mLib.deleteMovie(oldMovie); additionSuccessful = mLib.add(newMovie); result.put("result", deletionSuccessful & additionSuccessful); } } catch (Exception ex) { System.out.println("exception in callMethod: " + ex.getMessage()); } System.out.println("returning: " + result.toString()); return "HTTP/1.0 200 Data follows\nServer:localhost:8080\nContent-Type:text/plain\nContent-Length:" + (result.toString()).length() + "\n\n" + result.toString(); }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppObj.java
public static DbObject fromPickerResult(Context context, String action, ResolveInfo resolveInfo, Intent pickerResult) {// w w w . j av a 2 s.c o m long[] contactIds = pickerResult.getLongArrayExtra("contacts"); String pkgName = resolveInfo.activityInfo.packageName; String className = resolveInfo.activityInfo.name; /** * TODO: * * Identity Firewall Goes Here. * Membership details can be randomized in one of many ways. * The app (scrabble) may see games a set of gamers play together. * The app may always see random ids * The app may always see stable ids * * Can also permute the cursor and member order. */ JSONArray participantIds = new JSONArray(); participantIds.put(App.instance().getLocalPersonId()); for (long id : contactIds) { Maybe<Contact> annoyingContact = Contact.forId(context, id); try { Contact contact = annoyingContact.get(); participantIds.put(contact.personId); } catch (NoValError e) { participantIds.put(Contact.UNKNOWN); } } JSONObject json = new JSONObject(); try { json.put(Multiplayer.OBJ_MEMBERSHIP, (participantIds)); json.put(ANDROID_ACTION, action); json.put(ANDROID_PACKAGE_NAME, pkgName); json.put(ANDROID_CLASS_NAME, className); } catch (JSONException e) { Log.d(TAG, "What? Impossible!", e); } return new DbObject(TYPE, json); }