List of usage examples for org.json JSONObject optString
public String optString(String key)
From source file:weathernotificationservice.wns.activities.MainActivity.java
private ParseResult parseTodayJson(String result) { try {//from w w w. ja v a 2 s .c o m JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { return ParseResult.CITY_NOT_FOUND; } String city = reader.getString("name"); String country = ""; JSONObject countryObj = reader.optJSONObject("sys"); if (countryObj != null) { country = countryObj.getString("country"); todayWeather.setSunrise(countryObj.getString("sunrise")); todayWeather.setSunset(countryObj.getString("sunset")); } todayWeather.setCity(city); todayWeather.setCountry(country); JSONObject coordinates = reader.getJSONObject("coord"); if (coordinates != null) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")) .putFloat("longitude", (float) coordinates.getDouble("lat")).commit(); } JSONObject main = reader.getJSONObject("main"); todayWeather.setTemperature(main.getString("temp")); todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = reader.getJSONObject("wind"); todayWeather.setWind(windObj.getString("speed")); if (windObj.has("deg")) { todayWeather.setWindDirectionDegree(windObj.getDouble("deg")); } else { Log.e("parseTodayJson", "No wind direction available"); todayWeather.setWindDirectionDegree(null); } todayWeather.setPressure(main.getString("pressure")); todayWeather.setHumidity(main.getString("humidity")); JSONObject rainObj = reader.optJSONObject("rain"); String rain; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = reader.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } todayWeather.setRain(rain); final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id"); todayWeather.setId(idString); todayWeather.setIcon( setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY))); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastToday", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:weathernotificationservice.wns.activities.MainActivity.java
public ParseResult parseLongTermJson(String result) { int i;//from w w w. j a v a 2 s. c o m try { JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { if (longTermWeather == null) { longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); } return ParseResult.CITY_NOT_FOUND; } longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); JSONArray list = reader.getJSONArray("list"); for (i = 0; i < list.length(); i++) { Weather weather = new Weather(); JSONObject listItem = list.getJSONObject(i); JSONObject main = listItem.getJSONObject("main"); weather.setDate(listItem.getString("dt")); weather.setTemperature(main.getString("temp")); weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = listItem.optJSONObject("wind"); if (windObj != null) { weather.setWind(windObj.getString("speed")); weather.setWindDirectionDegree(windObj.getDouble("deg")); } weather.setPressure(main.getString("pressure")); weather.setHumidity(main.getString("humidity")); JSONObject rainObj = listItem.optJSONObject("rain"); String rain = ""; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = listItem.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } weather.setRain(rain); final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id"); weather.setId(idString); final String dateMsString = listItem.getString("dt") + "000"; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(dateMsString)); weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY))); Calendar today = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { longTermTodayWeather.add(weather); } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) { longTermTomorrowWeather.add(weather); } else { longTermWeather.add(weather); } } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastLongterm", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:com.google.blockly.model.FieldAngle.java
public static FieldAngle fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_angle \"name\" attribute must not be empty."); }/*from w ww . j av a2s . com*/ return new FieldAngle(name, json.optInt("angle", 90)); }
From source file:com.basetechnology.s0.agentserver.field.HelpField.java
public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) { String type = fieldJson.optString("type"); if (type == null || !type.equals("string")) return null; String name = fieldJson.has("name") ? fieldJson.optString("name") : null; String help = fieldJson.has("help") ? fieldJson.optString("help") : null; return new HelpField(symbolTable, name, help); }
From source file:com.chaosinmotion.securechat.server.commands.AddDevice.java
/** * Add device request. Takes parameters for deviceid, pubkey, as well as * the user info.//from ww w. j a v a 2s . c o m * @param userinfo * @param requestParams * @return * @throws IOException * @throws SQLException * @throws ClassNotFoundException */ public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams) throws ClassNotFoundException, SQLException, IOException { String deviceid = requestParams.optString("deviceid"); String pubkey = requestParams.optString("pubkey"); /* * Attempt to insert a new user into the database */ Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try { c = Database.get(); /* * We now have the user index. Insert the device. Note that it is * highly unlikely we will have a UUID collision, but we verify * we don't by deleting any rows in the device table with the * specified UUID. The worse case scenario is a collision which * knocks someone else off the air. (The alternative would be * to accidentally send the wrong person duplicate messages.) * * Note that we don't actually use a device-identifying identifer, * choosing instead to pick a UUID, so we need to deal with * the possibility (however remote) of duplicate UUIDs. * * In the off chance we did have a collision, we also delete all * old messages to the device; that prevents messages from being * accidentally delivered. */ ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN " + " (SELECT Messages.messageid " + " FROM Messages, Devices " + " WHERE Messages.deviceid = Devices.deviceid " + " AND Devices.deviceuuid = ?)"); ps.setString(1, deviceid); ps.execute(); ps.close(); ps = null; ps = c.prepareStatement("DELETE FROM Devices WHERE deviceuuid = ?"); ps.setString(1, deviceid); ps.execute(); ps.close(); ps = null; ps = c.prepareStatement("INSERT INTO Devices " + " ( userid, deviceuuid, publickey ) " + "VALUES " + " ( ?, ?, ?)"); ps.setInt(1, userinfo.getUserID()); ps.setString(2, deviceid); ps.setString(3, pubkey); ps.execute(); /* * Complete; return result */ return true; } finally { if (rs != null) rs.close(); if (ps != null) ps.close(); if (c != null) c.close(); } }
From source file:org.b3log.xiaov.service.TuringQueryService.java
/** * Chat with Turing Robot./*from w w w . j ava 2 s .c o m*/ * * @param userName the specified user name * @param msg the specified message * @return robot returned message, return {@code null} if not found */ public String chat(final String userName, String msg) { if (StringUtils.isBlank(msg)) { return null; } if (msg.startsWith(XiaoVs.QQ_BOT_NAME + " ")) { msg = msg.replace(XiaoVs.QQ_BOT_NAME + " ", ""); } if (msg.startsWith(XiaoVs.QQ_BOT_NAME + "")) { msg = msg.replace(XiaoVs.QQ_BOT_NAME + "", ""); } if (msg.startsWith(XiaoVs.QQ_BOT_NAME + ",")) { msg = msg.replace(XiaoVs.QQ_BOT_NAME + ",", ""); } if (msg.startsWith(XiaoVs.QQ_BOT_NAME)) { msg = msg.replace(XiaoVs.QQ_BOT_NAME, ""); } if (StringUtils.isBlank(userName) || StringUtils.isBlank(msg)) { return null; } final HTTPRequest request = new HTTPRequest(); request.setRequestMethod(HTTPRequestMethod.POST); try { request.setURL(new URL(TURING_API)); final String body = "key=" + URLEncoder.encode(TURING_KEY, "UTF-8") + "&info=" + URLEncoder.encode(msg, "UTF-8") + "&userid=" + URLEncoder.encode(userName, "UTF-8"); request.setPayload(body.getBytes("UTF-8")); final HTTPResponse response = URL_FETCH_SVC.fetch(request); final JSONObject data = new JSONObject(new String(response.getContent(), "UTF-8")); final int code = data.optInt("code"); switch (code) { case 40001: case 40002: case 40007: LOGGER.log(Level.ERROR, data.optString("text")); return null; case 40004: return "??~"; case 100000: return data.optString("text"); case 200000: return data.optString("text") + " " + data.optString("url"); case 302000: String ret302000 = data.optString("text") + " "; final JSONArray list302000 = data.optJSONArray("list"); final StringBuilder builder302000 = new StringBuilder(); for (int i = 0; i < list302000.length(); i++) { final JSONObject news = list302000.optJSONObject(i); builder302000.append(news.optString("article")).append(news.optString("detailurl")) .append("\n\n"); } return ret302000 + " " + builder302000.toString(); case 308000: String ret308000 = data.optString("text") + " "; final JSONArray list308000 = data.optJSONArray("list"); final StringBuilder builder308000 = new StringBuilder(); for (int i = 0; i < list308000.length(); i++) { final JSONObject news = list308000.optJSONObject(i); builder308000.append(news.optString("name")).append(news.optString("detailurl")).append("\n\n"); } return ret308000 + " " + builder308000.toString(); default: LOGGER.log(Level.WARN, "Turing Robot default return [" + data.toString(4) + "]"); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Chat with Turing Robot failed", e); } return null; }
From source file:com.google.android.apps.muzei.api.internal.SourceState.java
public void readJson(JSONObject jsonObject) throws JSONException { JSONObject artworkJsonObject = jsonObject.optJSONObject("currentArtwork"); if (artworkJsonObject != null) { mCurrentArtwork = Artwork.fromJson(artworkJsonObject); }//from w w w . ja va 2 s .com mDescription = jsonObject.optString("description"); mWantsNetworkAvailable = jsonObject.optBoolean("wantsNetworkAvailable"); mUserCommands.clear(); JSONArray commandsSerialized = jsonObject.optJSONArray("userCommands"); if (commandsSerialized != null && commandsSerialized.length() > 0) { int length = commandsSerialized.length(); for (int i = 0; i < length; i++) { mUserCommands.add(UserCommand.deserialize(commandsSerialized.optString(i))); } } }
From source file:com.github.jberkel.pay.me.model.Purchase.java
/** * @param itemType the item type for this purchase, cannot be null. * @param jsonPurchaseInfo the JSON representation of this purchase * @param signature the signature/*w ww . jav a 2 s. co m*/ * @throws JSONException if the purchase cannot be parsed or is invalid. */ public Purchase(ItemType itemType, String jsonPurchaseInfo, String signature) throws JSONException { if (itemType == null) throw new IllegalArgumentException("itemType cannot be null"); mItemType = itemType; final JSONObject json = new JSONObject(jsonPurchaseInfo); mOrderId = json.optString(ORDER_ID); mPackageName = json.optString(PACKAGE_NAME); mSku = json.optString(PRODUCT_ID); mPurchaseTime = json.optLong(PURCHASE_TIME); mPurchaseState = json.optInt(PURCHASE_STATE); mDeveloperPayload = json.optString(DEVELOPER_PAYLOAD); mToken = json.optString(TOKEN, json.optString(PURCHASE_TOKEN)); mOriginalJson = jsonPurchaseInfo; mSignature = signature; mState = State.fromCode(mPurchaseState); if (TextUtils.isEmpty(mSku)) { throw new JSONException("SKU is empty"); } }
From source file:ezturner.limitvolume.billing.SkuDetails.java
public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType;/*from w ww .j a va2 s . c o m*/ mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mPriceAmountMicros = o.optLong("price_amount_micros"); mPriceCurrencyCode = o.optString("price_currency_code"); mTitle = o.optString("title"); mDescription = o.optString("description"); }
From source file:com.findcab.driver.object.DriverInfo.java
public DriverInfo(JSONObject jObject) { car_license = jObject.optString("car_license"); car_service_number = jObject.optString("car_service_number"); car_type = jObject.optString("car_type"); distance = jObject.optDouble("distance"); id = jObject.optInt("id"); lat = jObject.optDouble("lat"); lng = jObject.optDouble("lng"); mobile = jObject.optString("mobile"); name = jObject.optString("name"); password = jObject.optString("password"); rate = jObject.optInt("rate"); updated_at = jObject.optString("updated_at"); }