List of usage examples for org.json JSONArray get
public Object get(int index) throws JSONException
From source file:com.shampan.model.PageModel.java
public ResultEvent addPhotos(String pageId, String albumId, String photoInfoList) { try {/* www . j a v a 2s .c o m*/ MongoCollection<PagePhotoDAO> mongoCollection = DBConnection.getInstance().getConnection() .getCollection(Collections.PAGEPHOTOS.toString(), PagePhotoDAO.class); JSONArray photoArray = new JSONArray(photoInfoList); ArrayList<PagePhotoDAO> photoList = new ArrayList<PagePhotoDAO>(); String defaultImg = ""; String photoId = ""; String referenceId = ""; int newTotalImg = photoArray.length(); if (photoArray != null) { PagePhotoDAO photoInfoObj1 = new PagePhotoDAOBuilder().build(photoArray.get(0).toString()); defaultImg = photoInfoObj1.getImage(); photoId = photoInfoObj1.getPhotoId(); referenceId = photoInfoObj1.getReferenceId(); PageAlbumDAO albumInfo = new PageAlbumDAO(); albumInfo.setDefaultImg(defaultImg); albumInfo.setTotalImg(newTotalImg); albumInfo.setPhotoId(photoId); albumInfo.setReferenceId(referenceId); PageAlbumDAO oldAlbumInfo = getAlbumInfo(pageId, albumId); JSONObject resultJson = new JSONObject(); Boolean refernceId = false; Boolean statusUpdate = false; if (oldAlbumInfo != null) { if (oldAlbumInfo.getAlbumId().equals(albumId)) { if (oldAlbumInfo.getPhotoId() != null) { statusUpdate = true; int totalImg = newTotalImg + oldAlbumInfo.getTotalImg(); String coverId = PropertyProvider.get("PAGE_COVER_PHOTOS_ALBUM_ID"); String profileId = PropertyProvider.get("PAGE_PROFILE_PHOTOS_ALBUM_ID"); String timelineId = PropertyProvider.get("PAGE_TIMELINE_PHOTOS_ALBUM_ID"); if (albumId.equals(coverId)) { refernceId = true; } else if (albumId.equals(profileId)) { refernceId = true; } else if (albumId.equals(timelineId)) { refernceId = true; } editAlbumTotalImg(pageId, albumId, totalImg); } else { editAlbum(pageId, albumId, albumInfo.toString()); } } } else { if (albumId.equals(PropertyProvider.get("PAGE_TIMELINE_PHOTOS_ALBUM_ID"))) { albumInfo.setTitle(PropertyProvider.get("PAGE_TIMELINE_PHOTOS_ALBUM_TITLE")); } else if (albumId.equals(PropertyProvider.get("PAGE_PROFILE_PHOTOS_ALBUM_ID"))) { albumInfo.setTitle(PropertyProvider.get("PAGE_PROFILE_PHOTOS_ALBUM_TITLE")); } else if (albumId.equals(PropertyProvider.get("PAGE_COVER_PHOTOS_ALBUM_ID"))) { albumInfo.setTitle(PropertyProvider.get("PAGE_COVER_PHOTOS_ALBUM_TITLE")); } albumInfo.setPageId(pageId); albumInfo.setAlbumId(albumId); createAlbum(albumInfo.toString()); } List<String> images = new ArrayList<>(); for (int i = 0; i < newTotalImg; i++) { PagePhotoDAO photoInfoObj = new PagePhotoDAOBuilder().build(photoArray.get(i).toString()); photoInfoObj.setPageId(pageId); photoInfoObj.setCreatedOn(utility.getCurrentTime()); photoInfoObj.setModifiedOn(utility.getCurrentTime()); photoInfoObj.setReferenceId(referenceId); photoList.add(photoInfoObj); if (refernceId != true && statusUpdate != false) { images.add(photoInfoObj.getImage()); } } if (refernceId != true && statusUpdate != false) { referenceId = oldAlbumInfo.getReferenceId(); StatusModel statusModel = new StatusModel(); ResultEvent rEvent = statusModel.updateStatusPhoto(referenceId, images.toString()); if (rEvent.getResponseCode().equals(PropertyProvider.get("SUCCESSFUL_OPERATION"))) { } } mongoCollection.insertMany(photoList); PageDAO pageInfo = getPageBasicInfo(pageId); if (pageInfo != null) { this.getResultEvent().setResult(pageInfo.getTitle()); } this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION")); } else { this.getResultEvent().setResponseCode(PropertyProvider.get("NULL_POINTER_EXCEPTION")); } } catch (Exception ex) { this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION")); } return this.resultEvent; }
From source file:com.oneteam.framework.android.location.direction.parser.DirectionsJSONParser.java
/** * Receives a JSONObject and returns a GDirection * // w ww. j a v a2 s. co m * @param jObject * The Json to parse * @return The GDirection defined by the JSon Object */ public List<GDirection> parse(JSONObject jObject) { // The returned direction List<GDirection> directionsList = new ArrayList<GDirection>(); // The current GDirection GDirection currentGDirection = null; // The legs List<GDLegs> legs = new ArrayList<GDLegs>(); // The current leg GDLegs currentLeg = null; // The paths List<GDPath> paths = new ArrayList<GDPath>(); // The current path GDPath currentPath = null; // JSON Array representing Routes JSONArray jRoutes = null; JSONObject jRoute; JSONObject jBound; // JSON Array representing Legs JSONArray jLegs = null; JSONObject jLeg; // JSON Array representing Step JSONArray jSteps = null; JSONObject jStep; String polyline = ""; try { jRoutes = jObject.getJSONArray("routes"); Log.v(tag, "routes found : " + jRoutes.length()); /** Traversing all routes */ for (int i = 0; i < jRoutes.length(); i++) { jRoute = (JSONObject) jRoutes.get(i); jLegs = jRoute.getJSONArray("legs"); Log.v(tag, "routes[" + i + "]contains jLegs found : " + jLegs.length()); /** Traversing all legs */ for (int j = 0; j < jLegs.length(); j++) { jLeg = (JSONObject) jLegs.get(j); jSteps = jLeg.getJSONArray("steps"); Log.v(tag, "routes[" + i + "]:legs[" + j + "] contains jSteps found : " + jSteps.length()); /** Traversing all steps */ for (int k = 0; k < jSteps.length(); k++) { jStep = (JSONObject) jSteps.get(k); polyline = (String) ((JSONObject) (jStep).get("polyline")).get("points"); // Build the List of GDPoint that define the path List<GDPoint> list = decodePoly(polyline); // Create the GDPath currentPath = new GDPath(list); currentPath.setDistance(((JSONObject) jStep.get("distance")).getInt("value")); currentPath.setDuration(((JSONObject) jStep.get("duration")).getInt("value")); currentPath.setHtmlText(jStep.getString("html_instructions")); currentPath.setTravelMode(jStep.getString("travel_mode")); Log.v(tag, "routes[" + i + "]:legs[" + j + "]:Step[" + k + "] contains Points found : " + list.size()); // Add it to the list of Path of the Direction paths.add(currentPath); } // currentLeg = new GDLegs(paths); currentLeg.setmDistance(((JSONObject) jLeg.get("distance")).getInt("value")); currentLeg.setmDuration(((JSONObject) jLeg.get("duration")).getInt("value")); currentLeg.setmEndAddress(jLeg.getString("end_address")); currentLeg.setmStartAddress(jLeg.getString("start_address")); legs.add(currentLeg); Log.v(tag, "Added a new Path and paths size is : " + paths.size()); } // Build the GDirection using the paths found currentGDirection = new GDirection(legs); jBound = (JSONObject) jRoute.get("bounds"); currentGDirection .setmNorthEastBound(new LatLng(((JSONObject) jBound.get("northeast")).getDouble("lat"), ((JSONObject) jBound.get("northeast")).getDouble("lng"))); currentGDirection .setmSouthWestBound(new LatLng(((JSONObject) jBound.get("southwest")).getDouble("lat"), ((JSONObject) jBound.get("southwest")).getDouble("lng"))); currentGDirection.setCopyrights(jRoute.getString("copyrights")); directionsList.add(currentGDirection); } } catch (JSONException e) { Log.e(tag, "Parsing JSon from GoogleDirection Api failed, see stack trace below:", e); } catch (Exception e) { Log.e(tag, "Parsing JSon from GoogleDirection Api failed, see stack trace below:", e); } return directionsList; }
From source file:ti.notificare.NotificareTitaniumAndroidModule.java
/** * Transform a JSONArray into an Object[] * @see NotificareTitaniumAndroidModule#jsonToObject(Object) for mapping details * @param json// w w w .j a v a2s. c om * @return */ private static Object[] jsonToArray(JSONArray json) { List<Object> elements = new ArrayList<Object>(json.length()); for (int i = 0; i < json.length(); i++) { try { Object value = json.get(i); elements.add(jsonToObject(value)); } catch (JSONException e) { Log.e(TAG, "JSON error: " + e.getMessage()); } } return elements.toArray(new Object[json.length()]); }
From source file:com.gamethrive.TrackGooglePurchase.java
TrackGooglePurchase(Activity activity, GameThrive inGameThrive) { appContext = activity;/*from w w w . ja v a 2s . c om*/ gameThrive = inGameThrive; SharedPreferences prefs = appContext.getSharedPreferences("GTPlayerPurchases", Context.MODE_PRIVATE); prefsEditor = prefs.edit(); purchaseTokens = new ArrayList<String>(); try { JSONArray jsonPurchaseTokens = new JSONArray(prefs.getString("purchaseTokens", "[]")); for (int i = 0; i < jsonPurchaseTokens.length(); i++) purchaseTokens.add(jsonPurchaseTokens.get(i).toString()); newAsExisting = (jsonPurchaseTokens.length() == 0); if (newAsExisting) newAsExisting = prefs.getBoolean("ExistingPurchases", true); } catch (JSONException e) { e.printStackTrace(); } trackIAP(); }
From source file:winnipegtransit.TransitConnection.java
private static void buildScheduleInfo(String stopNo) throws IOException, org.json.JSONException, NullPointerException, MalformedURLException { //storage variables used for storing information during processing String name = null;//w ww .j a v a2 s .co m Object unknownType; Object anotherUnknownType; JSONArray routeScheduleArray; JSONObject routeScheduleObject; JSONObject routeInfo = null; JSONObject allSchedules; JSONObject bus; JSONObject singleRoute; ArrayList<BusArrival> arrivals; ArrayList<ScheduleItem> scheduleItems; String arrival; String busName; String routeName; Date arrivalTime; JSONObject stop; JSONObject geo; JSONArray schedules; URL stopScheduleInfoURL; JSONObject scheduleInfo; StopInfo stopInfo; //build the URL object for the information that we need to retrieve, patching in the stop number passed in //as a parameter stopScheduleInfoURL = new URL( WT_URL + "stops/" + stopNo + "/schedule.json?max-results-per-route=3&" + API_KEY); //retreve the schedule JSON string from the web using the retrieveFromWeb method scheduleInfo = retrieveFromWeb(stopScheduleInfoURL); //get a JSON object containting the stop information stop = scheduleInfo.getJSONObject("stop-schedule").getJSONObject("stop"); //create a JSON Object containing the geographic information geo = stop.getJSONObject("centre").getJSONObject("geographic"); //retrieve specific stop information from the stop and geo JSON objects. String stopName = stop.getString("name"); String latitude = geo.getString("latitude"); String longitude = geo.getString("longitude"); //create a stopInfo object from the name, lattitude and longitude //will be built into a Schedule object further into the class stopInfo = new StopInfo(stopName, latitude, longitude); //get a JSON Object containging the route schedule information for the stop allSchedules = scheduleInfo.getJSONObject("stop-schedule").getJSONObject("route-schedules"); //in order to determine if the route schedule information is stored in an Object or an Array //get the route schedule object and place it into a generic Object. //then test to see if it is an instance of a JSONArray or JSONObject and take appropriate //action unknownType = allSchedules.get("route-schedule"); //if it is a JSONObject, then no array is present and cannot be iterated. if (unknownType instanceof JSONObject) { //cast the unknownType into a JSONObject routeScheduleObject = (JSONObject) unknownType; //get the route info into another object routeInfo = routeScheduleObject.getJSONObject("route"); //extract the name fro the routeInfo object name = routeInfo.getString("name"); //get the single route stop information from the routeSchedue object. singleRoute = routeScheduleObject.getJSONObject("scheduled-stops"); //get the array containing the scheduled stop information routeScheduleArray = singleRoute.getJSONArray("scheduled-stop"); //create a new scheduleItem array list scheduleItems = new ArrayList<ScheduleItem>(); //create a new BusArrival array list arrivals = new ArrayList<BusArrival>(); //for every item in the routeSchedule array for (int j = 0; j < routeScheduleArray.length(); j++) { //extract the bus object from the array at the current position bus = routeScheduleArray.getJSONObject(j); //and then store the bus name in a variable busName = bus.getJSONObject("variant").getString("name"); //then get the time information for the current bus. try { //there are cases where a bus only has a departure time, and not an arrival time. I let the JSONException handle //these cases. arrival = bus.getJSONObject("times").getJSONObject("arrival").getString("estimated"); } catch (JSONException jex) { arrival = bus.getJSONObject("times").getJSONObject("departure").getString("estimated"); } //convert the arrival time string into a date object arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a BusArrival object to the arrivals Array List arrivals.add(new BusArrival(busName, arrivalTime)); } //when all arrivals are processed, add a new schedule item to the scheduleItems array list //there will only be one item. I might change this around later. scheduleItems.add(new ScheduleItem(name, arrivals)); //create the new schedule item sc = new Schedule(scheduleItems, stopInfo, stopFeats); } //if its a JSONArray else if (unknownType instanceof JSONArray) { //cast the generic object into a JSONArray object routeScheduleArray = (JSONArray) unknownType; //only gets the first route. routeInfo = routeScheduleArray.getJSONObject(1).getJSONObject("route"); //create a new ScheduleItem array list scheduleItems = new ArrayList<ScheduleItem>(); //for every item in the route schedule array for (int i = 0; i < routeScheduleArray.length(); i++) { //we need to again test to see if the item retrieved is an Array or an Object anotherUnknownType = routeScheduleArray.getJSONObject(i).getJSONObject("scheduled-stops") .get("scheduled-stop"); //if its an object if (anotherUnknownType instanceof JSONObject) { //cast the generic object into a JSONObject routeScheduleObject = (JSONObject) anotherUnknownType; //extract the current route's name routeName = routeScheduleArray.getJSONObject(i).getJSONObject("route").getString("name"); //create a new BusArrival array list arrivals = new ArrayList<BusArrival>(); //extract the bus name and arrival time from the routeScheduleObject busName = routeScheduleObject.getJSONObject("variant").getString("name"); arrival = routeScheduleObject.getJSONObject("times").getJSONObject("arrival") .getString("estimated"); arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a new BusArrival to the arrivals array list arrivals.add(new BusArrival(busName, arrivalTime)); //trim it down to its actual size arrivals.trimToSize(); //add a new scheduleItem using the route name and arrivals array list scheduleItems.add(new ScheduleItem(routeName, arrivals)); } //however, if it is an Array else { //get the scheduled stops from the scheduled-stop array schedules = routeScheduleArray.getJSONObject(i).getJSONObject("scheduled-stops") .getJSONArray("scheduled-stop"); //extract the routes name routeName = routeScheduleArray.getJSONObject(i).getJSONObject("route").getString("name"); //create a new arrayList of BusArrival objects arrivals = new ArrayList<BusArrival>(); //for every item in the schedules array for (int j = 0; j < schedules.length(); j++) { //get the current bus object bus = schedules.getJSONObject(j); //and the bus name busName = bus.getJSONObject("variant").getString("name"); //gets set three times. thats ok. //get the busses arrival time try { //there are cases where a bus only has a departure time, and not an arrival time. I let the JSONException handle //these cases. arrival = bus.getJSONObject("times").getJSONObject("arrival").getString("estimated"); } catch (JSONException jex) { arrival = bus.getJSONObject("times").getJSONObject("departure").getString("estimated"); } //parse the arrival time into a date object arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a new BusArrival object to the arrivals Array list arrivals.add(new BusArrival(busName, arrivalTime)); } //when all schedule items are processed arrivals.trimToSize(); //add a new schedule item using the route name and arrivals array list scheduleItems.add(new ScheduleItem(routeName, arrivals)); } } //trim the schedule items array list scheduleItems.trimToSize(); //build a new Schedule object using the scheduleItems Array list, stopInformation object, //and stopFeatures Array List sc = new Schedule(scheduleItems, stopInfo, stopFeats); } }
From source file:org.jabsorb.serializer.AccessibleObjectResolver.java
/** * Creates a signature for an array of arguments * * @param arguments The argumnts/* w w w.j av a2 s.c o m*/ * @return A comma seperated string listing the arguments */ private static String argSignature(JSONArray arguments) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < arguments.length(); i += 1) { if (i > 0) { buf.append(","); } Object jso; try { jso = arguments.get(i); } catch (JSONException e) { throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e); } if (jso == null) { buf.append("java.lang.Object"); } else if (jso instanceof String) { buf.append("java.lang.String"); } else if (jso instanceof Number) { buf.append("java.lang.Number"); } else if (jso instanceof JSONArray) { buf.append("java.lang.Object[]"); } else { buf.append("java.lang.Object"); } } return buf.toString(); }
From source file:org.jabsorb.serializer.AccessibleObjectResolver.java
/** * Tries to unmarshall the arguments to a method * * @param accessibleObject The method/constructor to unmarshall the arguments * for./*from ww w . ja v a2s . c om*/ * @param arguments The arguments to unmarshall * @param parameterTypes The parameters of the method/construcot * @param serializer The main json serialiser. * @return The MethodCandidate that should suit the arguements and method. * @throws UnmarshallException If one of the arguments cannot be unmarshalled */ private static AccessibleObjectCandidate tryUnmarshallArgs(AccessibleObject accessibleObject, JSONArray arguments, Class[] parameterTypes, JSONSerializer serializer) throws UnmarshallException { int i = 0; ObjectMatch[] matches = new ObjectMatch[parameterTypes.length]; try { int nonLocalArgIndex = 0; for (; i < parameterTypes.length; i++) { SerializerState serialiserState = new SerializerState(); if (LocalArgController.isLocalArg(parameterTypes[i])) { // TODO: do this on the actual candidate? matches[i] = ObjectMatch.OKAY; } else { matches[i] = serializer.tryUnmarshall(serialiserState, parameterTypes[i], arguments.get(nonLocalArgIndex++)); } } } catch (JSONException e) { throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e); } catch (UnmarshallException e) { throw new UnmarshallException("arg " + (i + 1) + " " + e.getMessage(), e); } AccessibleObjectCandidate candidate = new AccessibleObjectCandidate(accessibleObject, parameterTypes, matches); return candidate; }
From source file:org.jabsorb.serializer.AccessibleObjectResolver.java
/** * Convert the arguments to a method call from json into java objects to be * used for invoking the method, later./* www .j ava2s. co m*/ * * @param context the context of the caller. This will be the servlet request * and response objects in an http servlet call environment. These * are used to insert local arguments (e.g. the request, response or * session,etc.) when found in the java method call argument * signature. * @param param the classes of the arguments to the function. * @param arguments the arguments from the caller, in json format. * @param serializer The main json serializer. * @return the java arguments as unmarshalled from json. * @throws UnmarshallException if there is a problem unmarshalling the * arguments. */ private static Object[] unmarshallArgs(Object context[], Class[] param, JSONArray arguments, JSONSerializer serializer) throws UnmarshallException { Object javaArgs[] = new Object[param.length]; int i = 0, j = 0; try { for (; i < param.length; i++) { SerializerState serializerState = new SerializerState(); if (LocalArgController.isLocalArg(param[i])) { javaArgs[i] = LocalArgController.resolveLocalArg(context, param[i]); } else { javaArgs[i] = serializer.unmarshall(serializerState, param[i], arguments.get(j++)); } } } catch (JSONException e) { throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e); } catch (UnmarshallException e) { throw new UnmarshallException("arg " + (i + 1) + " could not unmarshall", e); } return javaArgs; }
From source file:com.hichinaschool.flashcards.libanki.Utils.java
/** Given a list of integers, return a string '(int1,int2,...)'. */ public static String ids2str(JSONArray ids) { StringBuilder str = new StringBuilder(512); str.append("("); if (ids != null) { int len = ids.length(); for (int i = 0; i < len; i++) { try { if (i == (len - 1)) { str.append(ids.get(i)); } else { str.append(ids.get(i)).append(","); }/*from w w w .j a v a2 s . c o m*/ } catch (JSONException e) { Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage()); } } } str.append(")"); return str.toString(); }
From source file:com.hichinaschool.flashcards.libanki.Models.java
public void remField(JSONObject m, JSONObject field) { mCol.modSchema();/* w w w. j av a2s . c om*/ try { JSONArray ja = m.getJSONArray("flds"); JSONArray ja2 = new JSONArray(); int idx = -1; for (int i = 0; i < ja.length(); ++i) { if (field.equals(ja.getJSONObject(i))) { idx = i; continue; } ja2.put(ja.get(i)); } m.put("flds", ja2); int sortf = m.getInt("sortf"); if (sortf >= m.getJSONArray("flds").length()) { m.put("sortf", sortf - 1); } _updateFieldOrds(m); _transformFields(m, new TransformFieldDelete(idx)); if (idx == sortIdx(m)) { // need to rebuild mCol.updateFieldCache(Utils.toPrimitive(nids(m))); } renameField(m, field, null); } catch (JSONException e) { throw new RuntimeException(e); } }