List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
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 w w w . j a v a 2s . c o m 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 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/* w ww.j a v a 2 s . c o 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:tom.udacity.sample.sunrise.WeatherDataParser.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us.// w w w. j av a2 s . c o m */ public String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationQuery) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DATETIME = "dt"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); String[] resultStrs = new String[numDays]; for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime = dayForecast.getLong(OWM_DATETIME); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; }
From source file:tom.udacity.sample.sunrise.WeatherDataParser.java
/** * Given a string of the form returned by the api call: * http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7 * retrieve the maximum temperature for the day indicated by dayIndex * (Note: 0-indexed, so 0 would refer to the first day). *///w ww.j a v a2s . c o m private static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex) throws JSONException { JSONObject data = new JSONObject(weatherJsonStr); JSONArray days = data.getJSONArray("list"); JSONObject dayJson = days.getJSONObject(dayIndex); JSONObject temp = dayJson.getJSONObject("temp"); return temp.getDouble("max"); }
From source file:io.s4.client.Driver.java
/** * Initialize the driver./* w w w .ja v a2 s. c om*/ * * Handshake with adapter to receive a unique id, and verify that the driver * is compatible with the protocol used by the adapter. This does not * actually establish a connection for sending and receiving events. * * @see #connect(ReadMode, WriteMode) * * @return true if and only if the adapter issued a valid ID to this client, * and the protocol is found to be compatible. * @throws IOException * if the underlying TCP/IP socket throws an exception. */ public boolean init() throws IOException { if (state.isInitialized()) return true; try { sock = new Socket(hostname, port); ByteArrayIOChannel io = new ByteArrayIOChannel(sock); io.send(emptyBytes); byte[] b = io.recv(); if (b == null || b.length == 0) { if (debug) { System.err.println("Empty response during initialization."); } return false; } JSONObject json = new JSONObject(new String(b)); this.uuid = json.getString("uuid"); JSONObject proto = json.getJSONObject("protocol"); if (!isCompatible(proto)) { if (debug) { System.err.println("Driver not compatible with adapter protocol: " + proto); } return false; } state = State.Initialized; return true; } catch (JSONException e) { if (debug) { System.err.println("malformed JSON in initialization response. " + e); } e.printStackTrace(); return false; } finally { sock.close(); } }
From source file:com.trellmor.berrytube.BerryTubeIOCallback.java
/** * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge, * java.lang.Object[])// ww w .ja v a 2 s. co m */ public void on(String event, IOAcknowledge ack, Object... args) { if (event.compareTo("chatMsg") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject jsonMsg = (JSONObject) args[0]; try { berryTube.getHandler() .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg")))); } catch (JSONException e) { Log.e(TAG, "chatMsg", e); } } else Log.w(TAG, "chatMsg message is not a JSONObject"); } else if (event.compareTo("setNick") == 0) { if (args.length >= 1 && args[0] instanceof String) { berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0])); } else Log.w(TAG, "setNick message is not a String"); } else if (event.compareTo("loginError") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject error = (JSONObject) args[0]; berryTube.getHandler() .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed"))); } } else if (event.compareTo("userJoin") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "userJoin", e); } } else Log.w(TAG, "userJoin message is not a JSONObject"); } else if (event.compareTo("newChatList") == 0) { berryTube.getHandler().post(berryTube.new UserResetTask()); if (args.length >= 1 && args[0] instanceof JSONArray) { JSONArray users = (JSONArray) args[0]; for (int i = 0; i < users.length(); i++) { JSONObject user = users.optJSONObject(i); if (user != null) { try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "newChatList", e); } } } } else Log.w(TAG, "newChatList message is not a JSONArray"); } else if (event.compareTo("userPart") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_PART)); } catch (JSONException e) { Log.e(TAG, "userPart", e); } } else Log.w(TAG, "userPart message is not a JSONObject"); } else if (event.compareTo("drinkCount") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject drinks = (JSONObject) args[0]; berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks"))); } } else if (event.compareTo("kicked") == 0) { berryTube.getHandler().post(berryTube.new KickedTask()); } else if (event.compareTo("newPoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; ChatMessage msg; // Send chat message for new poll try { msg = new ChatMessage(poll.getString("creator"), poll.getString("title"), ChatMessage.EMOTE_POLL, 0, 0, false, 1); berryTube.getHandler().post(berryTube.new ChatMsgTask(msg)); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } // Create new poll try { berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll))); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } } } else if (event.compareTo("updatePoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; try { JSONArray votes = poll.getJSONArray("votes"); int[] voteArray = new int[votes.length()]; for (int i = 0; i < votes.length(); i++) { voteArray[i] = votes.optInt(i, -1); } berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray)); } catch (JSONException e) { Log.e(TAG, "updatePoll", e); } } } else if (event.compareTo("clearPoll") == 0) { berryTube.getHandler().post(berryTube.new ClearPollTask()); } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject videoMsg = (JSONObject) args[0]; try { JSONObject video = videoMsg.getJSONObject("video"); String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8"); String id = video.getString("videoid"); String type = video.getString("videotype"); berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type)); } catch (JSONException | UnsupportedEncodingException e) { Log.w(TAG, e); } } } }
From source file:com.facebook.internal.BundleJSONConverterTest.java
@Test public void testSimpleValues() throws JSONException { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1st"); arrayList.add("2nd"); arrayList.add("third"); Bundle innerBundle1 = new Bundle(); innerBundle1.putInt("inner", 1); Bundle innerBundle2 = new Bundle(); innerBundle2.putString("inner", "2"); innerBundle2.putStringArray("deep list", new String[] { "7", "8" }); innerBundle1.putBundle("nested bundle", innerBundle2); Bundle b = new Bundle(); b.putBoolean("boolValue", true); b.putInt("intValue", 7); b.putLong("longValue", 5000000000l); b.putDouble("doubleValue", 3.14); b.putString("stringValue", "hello world"); b.putStringArray("stringArrayValue", new String[] { "first", "second" }); b.putStringArrayList("stringArrayListValue", arrayList); b.putBundle("nested", innerBundle1); JSONObject json = BundleJSONConverter.convertToJSON(b); assertNotNull(json);/*from w w w .ja v a 2 s . c o m*/ assertEquals(true, json.getBoolean("boolValue")); assertEquals(7, json.getInt("intValue")); assertEquals(5000000000l, json.getLong("longValue")); assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", json.getString("stringValue")); JSONArray jsonArray = json.getJSONArray("stringArrayValue"); assertEquals(2, jsonArray.length()); assertEquals("first", jsonArray.getString(0)); assertEquals("second", jsonArray.getString(1)); jsonArray = json.getJSONArray("stringArrayListValue"); assertEquals(3, jsonArray.length()); assertEquals("1st", jsonArray.getString(0)); assertEquals("2nd", jsonArray.getString(1)); assertEquals("third", jsonArray.getString(2)); JSONObject innerJson = json.getJSONObject("nested"); assertEquals(1, innerJson.getInt("inner")); innerJson = innerJson.getJSONObject("nested bundle"); assertEquals("2", innerJson.getString("inner")); jsonArray = innerJson.getJSONArray("deep list"); assertEquals(2, jsonArray.length()); assertEquals("7", jsonArray.getString(0)); assertEquals("8", jsonArray.getString(1)); Bundle finalBundle = BundleJSONConverter.convertToBundle(json); assertNotNull(finalBundle); assertEquals(true, finalBundle.getBoolean("boolValue")); assertEquals(7, finalBundle.getInt("intValue")); assertEquals(5000000000l, finalBundle.getLong("longValue")); assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", finalBundle.getString("stringValue")); List<String> stringList = finalBundle.getStringArrayList("stringArrayValue"); assertEquals(2, stringList.size()); assertEquals("first", stringList.get(0)); assertEquals("second", stringList.get(1)); stringList = finalBundle.getStringArrayList("stringArrayListValue"); assertEquals(3, stringList.size()); assertEquals("1st", stringList.get(0)); assertEquals("2nd", stringList.get(1)); assertEquals("third", stringList.get(2)); Bundle finalInnerBundle = finalBundle.getBundle("nested"); assertEquals(1, finalInnerBundle.getInt("inner")); finalBundle = finalInnerBundle.getBundle("nested bundle"); assertEquals("2", finalBundle.getString("inner")); stringList = finalBundle.getStringArrayList("deep list"); assertEquals(2, stringList.size()); assertEquals("7", stringList.get(0)); assertEquals("8", stringList.get(1)); }
From source file:com.dvd.ui.AddCopy.java
private void addCopyDVDbtnActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addCopyDVDbtnActionPerformed String dvdCodeTxt = dvdCodeTxt1.getText(); String copyNumTxt = copyNumTxt1.getText(); String isleNumTxt = isleNumTxt1.getText(); String shelfNumTxt = shelfNumTxt1.getText(); if (!dvdCodeTxt.isEmpty() && !copyNumTxt.isEmpty() && !isleNumTxt.isEmpty() && !shelfNumTxt.isEmpty()) { try {//from w w w .jav a 2 s .c om if (isServiceOn) { String result = ""; String url1 = "http://localhost:8080/addCopyDVD?code=" + dvdCodeTxt + "©Number=" + copyNumTxt + "&isleNumber=" + isleNumTxt + "&shelfNumber=" + shelfNumTxt; // String q = URLEncoder.encode(url1, "UTF-8").replace("+", // "%20"); URL url = new URL(url1); URL obj = url; HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // con.setRequestProperty(CONTENT_LENGTH, // Integer.toString(content.getBytes().length)); con.setRequestProperty("Accept-Charset", "UTF-8"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); // optional default is GET con.setRequestMethod("POST"); // add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result result = response.toString(); // Parse to get translated text JSONObject jsonObject = new JSONObject(result); int code = jsonObject.getJSONObject("responseCode").getInt("code"); if (code == 201) { errorcopyLabel1.setForeground(Color.BLACK); errorcopyLabel1.setText("DVD Copy Successfully Added."); } else { errorcopyLabel1.setForeground(Color.RED); errorcopyLabel1.setText("Adding DVD Copy failed"); } } else { com.dvd.hibernate.repo.DVDRepository repository = new com.dvd.hibernate.repo.DVDRepository(); DVDCopyDao dvd = new DVDCopyDao(Integer.parseInt(copyNumTxt), isleNumTxt, shelfNumTxt, Integer.parseInt(dvdCodeTxt), "1"); repository.createCopyDVD(dvd); errorcopyLabel1.setForeground(Color.BLACK); errorcopyLabel1.setText("DVD Copy Successfully Added."); } } catch (Exception e) { errorcopyLabel1.setForeground(Color.RED); errorcopyLabel1.setText("Adding DVD Copy failed"); } } else { errorcopyLabel1.setForeground(Color.RED); errorcopyLabel1.setText("Adding DVD Copy failed"); } }
From source file:org.brickred.socialauth.provider.GoogleOAuth2Impl.java
private Profile authGoogleLogin() throws Exception { String presp;//from w w w. ja va2 s . c om try { Response response = authenticationStrategy.executeFeed(PROFILE_URL); presp = response.getResponseBodyAsString(Constants.ENCODING); } catch (Exception e) { throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e); } try { logger.debug("User Profile : " + presp); JSONObject resp = new JSONObject(presp); Profile p = new Profile(); p.setValidatedId(resp.getString("id")); p.setFirstName(resp.getString("given_name")); p.setLastName(resp.getString("family_name")); p.setEmail(resp.getString("email")); if (resp.has("location")) { p.setLocation(resp.getJSONObject("location").getString("name")); } if (resp.has("birthday")) { String bstr = resp.getString("birthday"); String[] arr = bstr.split("-"); BirthDate bd = new BirthDate(); if (arr.length > 0) { bd.setYear(Integer.parseInt(arr[2])); } if (arr.length > 1) { bd.setMonth(Integer.parseInt(arr[0])); } if (arr.length > 2) { bd.setDay(Integer.parseInt(arr[1])); } p.setDob(bd); } if (resp.has("gender")) { p.setGender(resp.getString("gender")); } if (resp.has("picture")) { p.setProfileImageURL(resp.getString("picture")); } if (resp.has("locale")) { String locale = resp.getString("locale"); if (locale != null) { String a[] = locale.split("-"); p.setLanguage(a[0]); if (a.length > 1) { p.setCountry(a[1]); } } } p.setProviderId(getProviderId()); userProfile = p; return p; } catch (Exception ex) { throw new ServerDataException("Failed to parse the user profile json : " + presp, ex); } }
From source file:org.protorabbit.Config.java
@SuppressWarnings("unchecked") private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) { try {/*w ww . j a va2 s .c o m*/ if (t.has("timeout")) { long templateTimeout = t.getLong("timeout"); temp.setTimeout(templateTimeout); } boolean tgzip = false; if (!devMode) { tgzip = gzip; } if (t.has("gzip")) { tgzip = t.getBoolean("gzip"); temp.setGzipStyles(tgzip); temp.setGzipScripts(tgzip); temp.setGzipTemplate(tgzip); } if (t.has("uniqueURL")) { Boolean unique = t.getBoolean("uniqueURL"); temp.setUniqueURL(unique); } // template overrides default combineResources if (t.has("combineResources")) { boolean combineResources = t.getBoolean("combineResources"); temp.setCombineResources(combineResources); temp.setCombineScripts(combineResources); temp.setCombineStyles(combineResources); } if (t.has("template")) { String turi = t.getString("template"); ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE); temp.setTemplateURI(templateURI); } if (t.has("namespace")) { temp.setURINamespace(t.getString("namespace")); } if (t.has("extends")) { List<String> ancestors = null; String base = t.getString("extends"); if (base.length() > 0) { String[] parentIds = null; if (base.indexOf(",") != -1) { parentIds = base.split(","); } else { parentIds = new String[1]; parentIds[0] = base; } ancestors = new ArrayList<String>(); for (int j = 0; j < parentIds.length; j++) { ancestors.add(parentIds[j].trim()); } } temp.setAncestors(ancestors); } if (t.has("overrides")) { List<TemplateOverride> overrides = new ArrayList<TemplateOverride>(); JSONArray joa = t.getJSONArray("overrides"); for (int z = 0; z < joa.length(); z++) { TemplateOverride tor = new TemplateOverride(); JSONObject toro = joa.getJSONObject(z); if (toro.has("test")) { tor.setTest(toro.getString("test")); } if (toro.has("uaTest")) { tor.setUATest(toro.getString("uaTest")); } if (toro.has("import")) { tor.setImportURI(toro.getString("import")); } overrides.add(tor); } temp.setTemplateOverrides(overrides); } if (t.has("scripts")) { JSONObject bsjo = t.getJSONObject("scripts"); processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI); } if (t.has("styles")) { JSONObject bsjo = t.getJSONObject("styles"); processURIResources(ResourceURI.LINK, bsjo, temp, baseURI); } if (t.has("properties")) { Map<String, IProperty> properties = null; JSONObject po = t.getJSONObject("properties"); properties = new HashMap<String, IProperty>(); Iterator<String> jit = po.keys(); while (jit.hasNext()) { String name = jit.next(); JSONObject so = po.getJSONObject(name); int type = IProperty.STRING; String value = so.getString("value"); if (so.has("type")) { String typeString = so.getString("type"); if ("string".equals(typeString.toLowerCase())) { type = IProperty.STRING; } else if ("include".equals(typeString.toLowerCase())) { type = IProperty.INCLUDE; } } IProperty pi = new Property(name, value, type, baseURI, temp.getId()); if (so.has("timeout")) { long timeout = so.getLong("timeout"); pi.setTimeout(timeout); } if (so.has("id")) { pi.setId(so.getString("id")); } if (so.has("uaTest")) { pi.setUATest(so.getString("uaTest")); } if (so.has("test")) { pi.setTest(so.getString("test")); } if (so.has("defer")) { pi.setDefer(so.getBoolean("defer")); } if (so.has("deferContent")) { pi.setDeferContent(new StringBuffer(so.getString("deferContent"))); } properties.put(name, pi); } temp.setProperties(properties); } } catch (JSONException e) { getLogger().log(Level.SEVERE, "Error parsing configuration.", e); } }