List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Parse multi JSON objects of type GroupCategory * //from w w w. java 2 s .c o m * @param json * @return * @throws JSONException */ public static List<GroupCategory> parseMultiGroupCategoryObjects(JSONObject json) throws JSONException { List<GroupCategory> groupCategories = null; if (json != null) { if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } groupCategories = new ArrayList<GroupCategory>(); JSONArray rows = json.getJSONArray(Const.ROWS); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); String key = row.getString(Const.KEY); if (!key.equals(Const.NULL)) { JSONObject groupCategoryJson = row.getJSONObject(Const.VALUE); GroupCategory groupCategory = sGsonExpose.fromJson(groupCategoryJson.toString(), GroupCategory.class); if (groupCategoryJson.has(Const.ATTACHMENTS)) { List<Attachment> attachments = new ArrayList<Attachment>(); JSONObject json_attachments = groupCategoryJson.getJSONObject(Const.ATTACHMENTS); @SuppressWarnings("unchecked") Iterator<String> keys = json_attachments.keys(); while (keys.hasNext()) { String attachmentKey = keys.next(); try { JSONObject json_attachment = json_attachments.getJSONObject(attachmentKey); Attachment attachment = sGsonExpose.fromJson(json_attachment.toString(), Attachment.class); attachment.setName(attachmentKey); attachments.add(attachment); } catch (JSONException e) { e.printStackTrace(); } } groupCategory.setAttachments(attachments); } groupCategories.add(groupCategory); } } } return groupCategories; }
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Find all messages for current user//from w w w .j a va 2 s . c om * * @param json * @return * @throws JSONException * @throws SpikaException * @throws IOException * @throws ClientProtocolException */ public static ArrayList<Message> findMessagesForUser(JSONObject json) throws JSONException, ClientProtocolException, IOException, SpikaException { ArrayList<Message> messages = null; if (json != null) { if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } messages = new ArrayList<Message>(); JSONArray rows = json.getJSONArray(Const.ROWS); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); JSONObject msgJson = row.getJSONObject(Const.VALUE); Message message = null; String messageType = msgJson.getString(Const.MESSAGE_TYPE); if (messageType.equals(Const.TEXT)) { message = new Gson().fromJson(msgJson.toString(), Message.class); } else if (messageType.equals(Const.IMAGE)) { message = parseMessageObject(msgJson, true, false, false); } else if (messageType.equals(Const.VOICE)) { message = parseMessageObject(msgJson, false, true, false); } else if (messageType.equals(Const.VIDEO)) { message = parseMessageObject(msgJson, false, false, true); } else if (messageType.equals(Const.EMOTICON)) { message = parseMessageObject(msgJson, false, false, false); } else { message = new Gson().fromJson(msgJson.toString(), Message.class); } if (message == null) { continue; } else { messages.add(message); } } } if (null != messages) { Collections.sort(messages); } return messages; }
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Parse a single JSON object of Message type * // www. j av a 2s. co m * @param json * @param image * @param voice * @return * @throws SpikaException * @throws JSONException * @throws IOException * @throws ClientProtocolException */ private static Message parseMessageObject(JSONObject json, boolean image, boolean voice, boolean video) throws ClientProtocolException, IOException, JSONException, SpikaException { Message message = new Message(); if (json == null) { return message; } if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } try { message.setId(json.getString(Const._ID)); } catch (JSONException e) { message.setId(""); } try { message.setRev(json.getString(Const._REV)); } catch (JSONException e) { message.setRev(""); } try { message.setType(json.getString(Const.TYPE)); } catch (JSONException e) { message.setType(""); } try { message.setMessageType(json.getString(Const.MESSAGE_TYPE)); } catch (JSONException e) { message.setMessageType(""); } try { message.setMessageTargetType(json.getString(Const.MESSAGE_TARGET_TYPE)); } catch (JSONException e) { message.setMessageTargetType(""); } try { message.setBody(json.getString(Const.BODY)); } catch (JSONException e) { message.setBody(""); } try { message.setFromUserId(json.getString(Const.FROM_USER_ID)); } catch (JSONException e) { message.setFromUserId(""); } try { message.setFromUserName(json.getString(Const.FROM_USER_NAME)); } catch (JSONException e) { message.setFromUserName(""); } try { message.setToUserId(json.getString(Const.TO_USER_ID)); } catch (JSONException e) { message.setToUserId(""); } try { message.setToGroupName(json.getString(Const.TO_USER_NAME)); } catch (JSONException e) { message.setToGroupName(""); } try { message.setToGroupId(json.getString(Const.TO_GROUP_ID)); } catch (JSONException e) { message.setToGroupId(""); } try { message.setToGroupName(json.getString(Const.TO_GROUP_NAME)); } catch (JSONException e) { message.setToGroupName(""); } try { message.setCreated(json.getLong(Const.CREATED)); } catch (JSONException e) { return null; } try { message.setModified(json.getLong(Const.MODIFIED)); } catch (JSONException e) { return null; } try { message.setValid(json.getBoolean(Const.VALID)); } catch (JSONException e) { message.setValid(true); } try { message.setAttachments(json.getJSONObject(Const.ATTACHMENTS).toString()); } catch (JSONException e) { message.setAttachments(""); } try { message.setLatitude(json.getString(Const.LATITUDE)); } catch (JSONException e) { message.setLatitude(""); } try { message.setLongitude(json.getString(Const.LONGITUDE)); } catch (JSONException e) { message.setLongitude(""); } try { message.setImageFileId((json.getString(Const.PICTURE_FILE_ID))); } catch (JSONException e) { message.setImageFileId(""); } try { message.setImageThumbFileId((json.getString(Const.PICTURE_THUMB_FILE_ID))); } catch (JSONException e) { message.setImageThumbFileId(""); } try { message.setVideoFileId((json.getString(Const.VIDEO_FILE_ID))); } catch (JSONException e) { message.setVideoFileId(""); } try { message.setVoiceFileId((json.getString(Const.VOICE_FILE_ID))); } catch (JSONException e) { message.setVoiceFileId(""); } try { message.setEmoticonImageUrl(json.getString(Const.EMOTICON_IMAGE_URL)); } catch (JSONException e) { message.setEmoticonImageUrl(""); } try { message.setAvatarFileId(json.getString(Const.AVATAR_THUMB_FILE_ID)); } catch (JSONException e) { message.setAvatarFileId(""); } try { message.setDeleteType(json.getInt(Const.DELETE_TYPE)); } catch (JSONException e) { message.setDeleteType(0); } try { message.setDelete(json.getInt(Const.DELETE_AT)); } catch (JSONException e) { message.setDelete(0); } try { message.setReadAt(json.getInt(Const.READ_AT)); } catch (JSONException e) { message.setReadAt(0); } try { message.setCommentCount(json.getInt(Const.COMMENT_COUNT)); } catch (JSONException e) { message.setCommentCount(0); } // if (image || video || voice) { // message.setCommentCount(CouchDB.getCommentCount(message.getId())); // } return message; }
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Parse multi comment objects/*from ww w .j av a2 s . c o m*/ * * @param json * @return * @throws JSONException */ public static List<Comment> parseMultiCommentObjects(JSONObject json) throws JSONException { List<Comment> comments = null; if (json != null) { if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } comments = new ArrayList<Comment>(); JSONArray rows = json.getJSONArray(Const.ROWS); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); String key = row.getString(Const.KEY); if (!"null".equals(key)) { JSONObject commentJson = row.getJSONObject(Const.VALUE); Comment comment = sGsonExpose.fromJson(commentJson.toString(), Comment.class); comments.add(comment); } } } return comments; }
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Parse multi emoticon objects/*from www . ja va2 s. c o m*/ * * @param json * @return * @throws JSONException */ public static List<Emoticon> parseMultiEmoticonObjects(JSONObject json) throws JSONException { List<Emoticon> emoticons = null; if (json != null) { if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } emoticons = new ArrayList<Emoticon>(); JSONArray rows = json.getJSONArray(Const.ROWS); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); String key = row.getString(Const.KEY); if (!"null".equals(key)) { JSONObject emoticonJson = row.getJSONObject(Const.VALUE); Emoticon emoticon = sGsonExpose.fromJson(emoticonJson.toString(), Emoticon.class); emoticons.add(emoticon); // SpikaApp.getFileDir().saveFile( // emoticon.getIdentifier(), // emoticon.getImageUrl()); } } } return emoticons; }
From source file:com.mercandalli.android.apps.files.main.Config.java
private void load(final Context context) { final String fileContent = FileUtils.readStringFile(context, FILE_NAME); if (fileContent == null) { return;/*from w w w .ja v a 2 s. c om*/ } try { JSONObject tmpJson = new JSONObject(fileContent); if (tmpJson.has("settings_1")) { JSONObject tmpSettings1 = tmpJson.getJSONObject("settings_1"); for (ENUM_Int enum_int : ENUM_Int.values()) { if (tmpSettings1.has(enum_int.key)) { enum_int.value = tmpSettings1.getInt(enum_int.key); } } for (ENUM_Boolean enum_boolean : ENUM_Boolean.values()) { if (tmpSettings1.has(enum_boolean.key)) { enum_boolean.value = tmpSettings1.getBoolean(enum_boolean.key); } } for (ENUM_String enum_string : ENUM_String.values()) { if (tmpSettings1.has(enum_string.key)) { enum_string.value = tmpSettings1.getString(enum_string.key); } } } } catch (JSONException e) { Log.e(getClass().getName(), "Failed to convert Json", e); } }
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Object getCoinValueBTC() { Date date = new Date(); long now = date.getTime(); //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;//from ww w . j a v a 2s. c o m String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=" + CoinDefinition.cryptsyMarketId; HttpURLConnection connectionCryptsy = null; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); Io.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker); JSONArray recenttrades = coinInfo.getJSONArray("recenttrades"); double btcTraded = 0.0; double coinTraded = 0.0; for (int i = 0; i < recenttrades.length(); ++i) { JSONObject trade = (JSONObject) recenttrades.get(i); btcTraded += trade.getDouble("total"); coinTraded += trade.getDouble("quantity"); } Double averageTrade = btcTraded / coinTraded; //Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", averageTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("BTC")) btcRate = averageTrade; } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } finally { if (connectionCryptsy != null) connectionCryptsy.disconnect(); } return null; }
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/*w w w .java 2 s . c om*/ try { Double btcRate = 0.0; boolean cryptsyValue = true; Object result = getCoinValueBTC(); if (result == null) { result = getCoinValueBTC_BTER(); cryptsyValue = false; if (result == null) return null; } btcRate = (Double) result; connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { String rateStr = o.optString(field, null); if (rateStr != null) { try { double rateForBTC = Double.parseDouble(rateStr); rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", "."); final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, url.getHost())); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {}: {}", new Object[] { currencyCode, url, x.getMessage() }); } } } } } log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start)); //Add Bitcoin information if (rates.size() == 0) { int i = 0; i++; } else { rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); rates.put("m" + CoinDefinition.cryptsyMarketCurrency, new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins( String.format("%.5f", btcRate * 1000).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); } return rates; } else { log.warn("http status {} when fetching {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.chess.genesis.dialog.GameStatsDialog.java
public GameStatsDialog(final Context context, final JSONObject json) { super(context, BaseDialog.CANCEL); String[] statusArr = null;/*from w w w .j av a 2s. com*/ String gametype = null, gameid = null, sign = null; int eventtype = 0, ycol = 0, w_from = 0, w_to = 0, b_from = 0, b_to = 0; try { gameid = json.getString("gameid"); ycol = json.getInt("yourcolor"); statusArr = STATUS_MAP.get(json.getInt("status") * ycol); gametype = json.getString("gametype"); gametype = gametype.substring(0, 1).toUpperCase(Locale.US) + gametype.substring(1); eventtype = Integer.parseInt(json.getString("eventtype")); if (ycol == Piece.WHITE) opponent = json.getString("black_name"); else opponent = json.getString("white_name"); if (eventtype != Enums.INVITE) { w_from = json.getJSONObject("white").getInt("from"); w_to = json.getJSONObject("white").getInt("to"); b_from = json.getJSONObject("black").getInt("from"); b_to = json.getJSONObject("black").getInt("to"); } } catch (final JSONException e) { throw new RuntimeException(e.getMessage(), e); } final int to = (ycol == Piece.WHITE) ? w_to : b_to; diff = (ycol == Piece.WHITE) ? (w_to - w_from) : (b_to - b_from); sign = (diff >= 0) ? "+" : "-"; title = statusArr[0]; result = statusArr[1]; psr_type = gametype + " PSR :"; if (eventtype == Enums.INVITE) psr_score = "None (Invite Game)"; else psr_score = sign + String.valueOf(Math.abs(diff)) + " (" + String.valueOf(to) + ')'; final GameDataDB db = new GameDataDB(context); db.archiveNetworkGame(gameid, w_from, w_to, b_from, b_to); db.close(); }
From source file:com.att.voice.AttDigitalLife.java
public Map<String, String> authtokens() { Map<String, String> authMap = new HashMap<>(); String json = ""; try {/*from w w w . j a v a2 s.c o m*/ URIBuilder builder = new URIBuilder(); builder.setScheme(HTTP_PROTOCOL).setHost(DIGITAL_LIFE_PATH).setPath("/penguin/api/authtokens") .setParameter(USER_ID_PARAMETER, username).setParameter(PASSWORD_PARAMETER, password) .setParameter(DOMAIN_PARAMETER, "DL").setParameter(APP_KEY_PARAMETER, APP_KEY); URI uri = builder.build(); HttpPost httpPost = new HttpPost(uri); HttpResponse httpResponse = httpclient.execute(httpPost); httpResponse.getEntity(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { json = EntityUtils.toString(entity); } JSONObject jsonObject = new JSONObject(json); JSONObject content = jsonObject.getJSONObject("content"); authMap.put("id", content.getJSONArray("gateways").getJSONObject(0).getString("id")); authMap.put("Authtoken", content.getString("authToken")); authMap.put("Requesttoken", content.getString("requestToken")); authMap.put("Appkey", APP_KEY); if (content.has("contact") && content.getJSONObject("contact").has("firstName") && content.getJSONObject("contact").has("lastName")) { authMap.put("name", content.getJSONObject("contact").getString("firstName") + " " + content.getJSONObject("contact").getString("lastName")); } return authMap; } catch (IOException | URISyntaxException ex) { Logger.getLogger(AttDigitalLife.class.getName()).log(Level.SEVERE, null, ex); } return null; }