List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java
PointOfInterest fromPoint(JSONObject point) throws JSONException { String type = point.getString("type"); double lat;//from w w w . j a v a2 s. c om double lng; if (type.equals("Point")) { JSONArray coords = point.getJSONArray("coordinates"); lng = coords.getDouble(0); lat = coords.getDouble(1); } else { throw new IllegalArgumentException(); } return new PoiBuilder(0, lat, lng, this.category).build(); }
From source file:edu.asu.msse.gnayak2.main.CollectionSkeleton.java
public String callMethod(String request) { JSONObject result = new JSONObject(); try {// w w 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:org.openmrs.mobile.listeners.visit.FindVisitsByPatientUUIDListener.java
@Override public void onResponse(JSONObject response) { mLogger.d(response.toString());//from www .j av a 2 s .com try { JSONArray visitResultJSON = response.getJSONArray(BaseManager.RESULTS_KEY); if (visitResultJSON.length() > 0) { for (int i = 0; i < visitResultJSON.length(); i++) { Visit visit = VisitMapper.map(visitResultJSON.getJSONObject(i)); long visitId = visitDAO.getVisitsIDByUUID(visit.getUuid()); if (visitId > 0) { visitDAO.updateVisit(visit, visitId, mPatientID); } else { visitDAO.saveVisit(visit, mPatientID); } } } } catch (JSONException e) { mErrorOccurred = true; mLogger.d(e.toString()); } finally { updateData(); } }
From source file:com.theaigames.game.warlight2.MapCreator.java
/** * @param mapString : string that represents the map to be created * @return : a Map object to use in the game */// w w w .java 2 s. c om public static Map createMap(String mapString) { Map map = new Map(); //parse the map string try { JSONObject jsonMap = new JSONObject(mapString); // create SuperRegion objects JSONArray superRegions = jsonMap.getJSONArray("SuperRegions"); for (int i = 0; i < superRegions.length(); i++) { JSONObject jsonSuperRegion = superRegions.getJSONObject(i); map.add(new SuperRegion(jsonSuperRegion.getInt("id"), jsonSuperRegion.getInt("bonus"))); } // create Region object JSONArray regions = jsonMap.getJSONArray("Regions"); for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); SuperRegion superRegion = map.getSuperRegion(jsonRegion.getInt("superRegion")); map.add(new Region(jsonRegion.getInt("id"), superRegion)); } // add the Regions' neighbors for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); Region region = map.getRegion(jsonRegion.getInt("id")); JSONArray neighbors = jsonRegion.getJSONArray("neighbors"); for (int j = 0; j < neighbors.length(); j++) { Region neighbor = map.getRegion(neighbors.getInt(j)); region.addNeighbor(neighbor); } } } catch (JSONException e) { System.err.println("JSON: Can't parse map string: " + e); } map.sort(); return map; }
From source file:org.b3log.rhythm.repository.impl.UserRepositoryImpl.java
@Override public JSONObject getByEmail(final String email) throws RepositoryException { final Query query = new Query().setPageCount(1); query.setFilter(new PropertyFilter(User.USER_EMAIL, FilterOperator.EQUAL, email.toLowerCase().trim())); try {/* ww w.j av a2 s .c o m*/ final JSONObject result = get(query); final JSONArray array = result.getJSONArray(Keys.RESULTS); if (0 == array.length()) { return null; } return array.getJSONObject(0); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); throw new RepositoryException(e); } }
From source file:com.example.pyrkesa.shwc.OngoingNotificationListenerService.java
@Override public void onDataChanged(DataEventBuffer dataEvents) { final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); final String ACTION_DEMAND = "ACTION_DEMAND"; String EXTRA_CMD = "EXTRA_CMD"; dataEvents.close();// ww w .j a va 2 s . c om if (!mGoogleApiClient.isConnected()) { ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS); if (!connectionResult.isSuccess()) { Log.e(TAG, "Service failed to connect to GoogleApiClient."); return; } } for (DataEvent event : events) { if (event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (PATH.equals(path)) { // Get the data out of the event DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); //final String title = dataMapItem.getDataMap().getString(KEY_TITLE); final String room_devices = dataMapItem.getDataMap().getString(KEY_ROOM_DEVICES); final String room_name = dataMapItem.getDataMap().getString(KEY_ROOM_NAME); // Asset asset = dataMapItem.getDataMap().getAsset(KEY_BACKGROUND); try { JSONObject roomJSON = new JSONObject(room_devices); JSONArray devicesArray = roomJSON.getJSONArray("devices"); String firstPageText = "quipements :"; ArrayList<Device> devicess = new ArrayList<Device>(); for (int i = 0; i < devicesArray.length(); i++) { JSONObject d = devicesArray.getJSONObject(i); Device device = new Device(d.getString("id"), d.getString("name"), d.getInt("type"), d.getString("status")); String Newline = System.getProperty("line.separator"); firstPageText += Newline; firstPageText += device.name; devicess.add(device); } if (firstPageText.equalsIgnoreCase("quipements :")) { firstPageText = "Aucun quipement"; } Bitmap background = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg_distance); NotificationCompat.WearableExtender notifExtender = new NotificationCompat.WearableExtender(); for (Device d : devicess) { try { notifExtender.addAction(d.getAction(OngoingNotificationListenerService.this)); } catch (Exception e) { Log.e("Erreur get Action :", e.getMessage()); } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle("Pice : " + roomJSON.getString("name")) .setContentText(firstPageText).setSmallIcon(R.drawable.mini_logo) .extend(notifExtender.setBackground(background)).setOngoing(true); // Build the notification and show it NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } catch (Throwable t) { Log.e("JSON_WEAR_SHWC", "Could not parse malformed JSON: " + room_devices + t.getMessage()); } } else { Log.d(TAG, "Unrecognized path: " + path); } } } }
From source file:com.example.wmgps.MainActivity.java
/** Called when the user clicks the Send button */ public void sendMessage(View view) { /*Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent);*///from ww w . j a v a 2 s.co m /*EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); TextView output = (TextView) findViewById(R.id.welcome); output.setText(message);*/ /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL)); startActivity(browserIntent); */ TextView hiddenText = (TextView) findViewById(R.id.Hidden11); if (Misc.isNullTrimmedString(hiddenText.getText().toString())) { TextView output = (TextView) findViewById(R.id.welcome1); boolean without_connection = true; Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed String response = Misc.EMPTY_STRING; String welcome1String = "*******************Connected*************************"; try { response = new RetrieveFeedTask().execute(new String[] {}).get(); } catch (Exception e) { response = Misc.EMPTY_STRING; Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } if (Misc.isNullTrimmedString(response)) { // welcome1String = "***Loading Static, couldn't connect***"; response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"}," + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10," + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"}," + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]" + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}"; } StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING); int currentOutputTag = R.id.Hidden1; int currentInputTag = R.id.edit_message; // Renderer::decodeConfig() if (!Misc.isNullTrimmedString(response)) { try { JSONObject jsonObj = new JSONObject(response); for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) { String name = (String) iterator.next(); JSONObject jsonObj1 = jsonObj.getJSONObject(name); for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) { String name1 = (String) iterator1.next(); if ("elements".equals(name1)) { JSONArray jsonArr = jsonObj1.getJSONArray(name1); boolean userName = false; boolean password = false; for (int i = 0; i < jsonArr.length(); i++) { JSONObject temp = jsonArr.getJSONObject(i); String initialValue = null; String initialName = null; String initialLabel = null; if (!temp.isNull("name") && temp.getString("name").equals("j_password")) { initialName = "j_password"; } else if (!temp.isNull("name") && temp.getString("name").equals("j_username")) { initialName = "j_username"; } for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) { String tempName = (String) iterator2.next(); String tempValue = (String) temp.getString(tempName); if (tempName.equals("type")) { if (tempValue.equals("label") || tempValue.equals("entry")) { initialLabel = tempValue; } } else if (tempName.equals("value")) { initialValue = tempValue; } /* if(tempName.equals("label")) { if(Misc.isNullTrimmedString(initialValue)) initialLabel = tempName; else { typeAndValueOfTag.put("output",initialValue); initialValue = Misc.EMPTY_STRING; continue; } } else if(tempName.equals("value")) { if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel)) { initialValue = tempValue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label")) { typeAndValueOfTag.put("output",tempValue); initialValue = Misc.EMPTY_STRING; continue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry")) { if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name")) typeAndValueOfTag.put("input",tempValue); else initialValue = tempValue; } } else if(tempName.equals("entry")) { if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel)) { initialName = tempName; } else typeAndValueOfTag.put("input",initialValue); finalEncodedString.append(" " + tempName + " " + tempValue + " ----- "); }*/ } if (initialLabel != null) { if (initialLabel.equals("label")) { if (initialValue.equals(" User ID: ")) { TextView output1 = (TextView) findViewById(R.id.userNameText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = true; password = false; } else if (initialValue.equals("Password: ")) { TextView output1 = (TextView) findViewById(R.id.passwordText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); password = true; userName = false; } else { TextView output1 = (TextView) findViewById(currentOutputTag++); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = false; password = false; } } else if (initialLabel.equals("entry")) { if ("j_password".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.passwordEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter password"); } } else if ("j_username".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.userNameEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter username"); } } else { EditText input = ((EditText) findViewById(currentInputTag++)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter value"); } else input.setText(initialValue); } } } /*if(initialLabel != null) { List<String> listOfValues; if(typeAndValueOfTag.containsKey(initialLabel)) { listOfValues = typeAndValueOfTag.get(initialLabel); listOfValues.add(initialValue); } typeAndValueOfTag.put(initialLabel,initialValue); }*/ } } else { // Here, just the URL would get processed. So don't use. // output.setText(" " + name + " " + jsonObj1.getString(name1)); } } } TextView welcome1 = (TextView) findViewById(R.id.welcome1); welcome1.setText(welcome1String); // processUIDisplay(typeAndValueOfTag); /*if(finalEncodedString.length() == 0) finalEncodedString.append("Could not process"); output.setText(finalEncodedString.toString()); TextView output2 = (TextView) findViewById(R.id.Hidden1); output2.setText("Hidden one is enabled"); output2.setVisibility(View.VISIBLE);*/ } catch (JSONException e) { Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } } hiddenText.setText("validated user"); /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"}, {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "}, {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10, "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true}, {"type":"break"},{"type":"label","value":"Password: "}, {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false}, {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"}, {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}] ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/ } else { List outputList = verifyUser(); if (!Misc.isNullList(outputList)) { String sessionId = (String) outputList.get(0); String userType = (String) outputList.get(1); Intent intent = new Intent(this, MenuActivity.class); if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType) && Integer.parseInt(sessionId) > 0) { if (userType.equals(Constants.WORKER)) { MenuActivity.sessionId = Misc.EMPTY_STRING; TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.WORKER); intent.putExtra(Constants.SESSION_ID, sessionId); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR); intent.putExtra(Constants.SESSION_ID, sessionId); } } // goto Maps screen // Get the message from the intent startActivity(intent); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText("Invalid Username/Password"); error.setVisibility(View.VISIBLE); } } return; }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an * instance of <code>JSONObject.NULL</code>. * * @param jsonObject The {@link JSONObject} being processed * @param field The field to retrieve//from ww w .j ava 2 s. c o m * @param fieldType The data type of the field * @return The field value (or null if not found) * * @param <T> The data type to return */ @SuppressWarnings("unchecked") protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field, final Class<T> fieldType) { T fieldValue = null; if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) { try { if (fieldType == String.class) { fieldValue = (T) jsonObject.getString(field); } else if (fieldType == Integer.class) { fieldValue = (T) Integer.valueOf(jsonObject.getInt(field)); } else if (fieldType == Long.class) { fieldValue = (T) Long.valueOf(jsonObject.getLong(field)); } else if (fieldType == Float.class) { fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field))); } else if (fieldType == JSONArray.class) { fieldValue = (T) jsonObject.getJSONArray(field); } else if (fieldType == JSONObject.class) { fieldValue = (T) jsonObject.getJSONObject(field); } else { fieldValue = (T) jsonObject.get(field); } } catch (final JSONException | ClassCastException e) { // TODO Log a warning } } return fieldValue; }
From source file:com.streaming.sweetplayer.fragment.ArtistFragment.java
private void getSongsList(ArrayList<HashMap<String, String>> parseList, String url) { JSONParser jsonParser = new JSONParser(); JSONArray jsonArray;// w w w .j av a 2 s . c om try { JSONObject json = jsonParser.getJSONFromUrl(url); if (json != null) { jsonArray = json.getJSONArray(mJsonItem); int array_length = jsonArray.length(); if (isSongsView) { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ARTIST, jsonObject.getString(Config.ARTIST)); map.put(Config.NAME, jsonObject.getString(Config.SONG)); map.put(Config.MP3, jsonObject.getString(Config.MP3)); map.put(Config.DURATION, jsonObject.getString(Config.DURATION)); map.put(Config.URL, jsonObject.getString(Config.URL)); map.put(Config.IMAGE, mImageForDB); parseList.add(map); } } else { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ALBUM, jsonObject.getString(Config.ALBUM)); map.put(Config.SONGS_ITEM, jsonObject.getString(Config.SONGS_ITEM)); map.put(Config.IMAGE, jsonObject.getString(Config.IMAGE)); map.put(Config.URL, jsonObject.getString(Config.URL)); parseList.add(map); } } } } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.vk.sdkweb.api.model.VKApiArray.java
@Override public VKApiModel parse(JSONObject object) { try {//from w w w .j a v a 2 s. c o m JSONArray jsonArray; if ((jsonArray = object.optJSONArray("response")) == null) { object = object.getJSONObject("response"); count = object.getInt("count"); jsonArray = object.getJSONArray("items"); } parse(jsonArray); } catch (JSONException e) { if (VKSdk.DEBUG) e.printStackTrace(); } fields = object; return this; }