List of usage examples for org.json JSONObject optJSONArray
public JSONArray optJSONArray(String key)
From source file:net.netheos.pcsapi.credentials.AppInfoFileRepository.java
public AppInfoFileRepository(File file) throws IOException { this.file = file; BufferedReader reader = null; try {/* www. j a va 2s. com*/ reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), PcsUtils.UTF8)); String line; while ((line = reader.readLine()) != null) { // while loop begins here line = line.trim(); if (line.startsWith("#") || line.length() == 0) { continue; } String[] appInfoArray = line.split("=", 2); // Key String[] appInfoKeyArray = appInfoArray[0].trim().split("\\."); String providerName = appInfoKeyArray[0]; String appName = appInfoKeyArray[1]; String appInfoValue = appInfoArray[1].trim(); JSONObject jsonObj = (JSONObject) new JSONTokener(appInfoValue).nextValue(); String appId = jsonObj.optString("appId", null); AppInfo appInfo; if (appId != null) { // OAuth JSONArray jsonScope = jsonObj.optJSONArray("scope"); List<String> scopeList = new ArrayList<String>(); for (int i = 0; i < jsonScope.length(); i++) { scopeList.add(jsonScope.get(i).toString()); } String appSecret = jsonObj.getString("appSecret"); String redirectUrl = jsonObj.optString("redirectUrl", null); appInfo = new OAuth2AppInfo(providerName, appName, appId, appSecret, scopeList, redirectUrl); } else { // Login / Password appInfo = new PasswordAppInfo(providerName, appName); } appInfoMap.put(getAppKey(providerName, appName), appInfo); } } finally { PcsUtils.closeQuietly(reader); } }
From source file:com.parking.billing.Security.java
/** * Verifies that the data was signed with the given signature, and returns * the list of verified purchases. The data is in JSON format and contains * a nonce (number used once) that we generated and that was signed * (as part of the whole data string) with a private key. The data also * contains the {@link PurchaseState} and product ID of the purchase. * In the general case, there can be an array of purchase transactions * because there may be delays in processing the purchase on the backend * and then several purchases can be batched together. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key *//*www.j a v a 2 s. c o m*/ public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return null; } if (BillingConstants.DEBUG) { Log.i(TAG, "signedData: " + signedData); } boolean verified = false; if (!TextUtils.isEmpty(signature)) { /** * Compute your public key (that you got from the Android Market publisher site). * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an adversary to replace the public key with one * of their own and then fake messages from the server. * * Generally, encryption keys / passwords should only be kept in memory * long enough to perform the operation they need to perform. */ //Chintan's Key String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRIrk/6nAPzZo5HKe261/ZMfoe63mtY5QUlc0A0/77RTicrS9Nk1VjtVniRpHmjasQOGsQrBpBGJUYp0ixsjJpgfjLv7OvpF8Hp/ucth2T/Bm7kl/odRDT3urAp3snvqZEzfOg1wtDU7DAnDW1zNSqVNCVczXRnNrEmGxEjamKkTTQwz37ui7AhjKXCXAJY4n5ANj1oymnjGN5FHfzcMb07wR/ucz39ZX+Raf6qBsbnYkmuDH6pJ/4ZI9+vjbgWzXCx07DefQW4dtNMQZlVlKgKnJUkafePUYJVIO4sRgeWL1e5b8dbIYMO7gB9oopyfVhZifi+pDGr5+YAxi6D3PwIDAQAB"; //Mandar's Key: //String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj7zgTswMi1ePyAK7rCnCOkpmviHZzoSn2cxtyQ5ZQRFifNGkKq3Gli3VbeIeeJR8GHzlfOPUSgtMrd17WtGJoo29rsw6UuXov+imQutGKZglcM/cIrlIdZCsse3dGYyDcKFhEHrC/nPdwlYxgIGBaZKAcbbhitkdgYaVHQvGFTagCytxDq9NDJAY7exSKKm2HimfjlcBZjhHeImZ+cRCPux+9uoBQ4mTRYjrXfcpi/OPKTKsq2AHXf/y60qsZJlgGl3tBgRQo6lOEr7UbbHKESTKvOQ4t3J1wjNz8Z3+T0PZHb5JkeTsdAE7cG7jmz2HmMxfdXcT5mBTTDei6DPDGwIDAQAB"; PublicKey key = Security.generatePublicKey(base64EncodedPublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject(signedData); // The nonce might be null if the user backed out of the buy page. nonce = jObject.optLong("nonce"); jTransactionsArray = jObject.optJSONArray("orders"); if (jTransactionsArray != null) { numTransactions = jTransactionsArray.length(); } } catch (JSONException e) { return null; } if (!Security.isNonceKnown(nonce)) { Log.w(TAG, "Nonce not found: " + nonce); return null; } ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>(); try { for (int i = 0; i < numTransactions; i++) { JSONObject jElement = jTransactionsArray.getJSONObject(i); int response = jElement.getInt("purchaseState"); PurchaseState purchaseState = PurchaseState.valueOf(response); String productId = jElement.getString("productId"); String packageName = jElement.getString("packageName"); long purchaseTime = jElement.getLong("purchaseTime"); String orderId = jElement.optString("orderId", ""); String notifyId = null; if (jElement.has("notificationId")) { notifyId = jElement.getString("notificationId"); } String developerPayload = jElement.optString("developerPayload", null); // If the purchase state is PURCHASED, then we require a // verified nonce. /** * mandarm - We are ok with no signature for our test code! */ //TODO - Take care for signed purchases. if (purchaseState == PurchaseState.PURCHASED && !verified) { continue; } purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload)); } } catch (JSONException e) { Log.e(TAG, "JSON exception: ", e); return null; } removeNonce(nonce); return purchases; }
From source file:co.marcin.novaguilds.util.StringUtils.java
public static List<String> jsonToList(String json) { json = "{array:" + json + "}"; JSONObject obj = new JSONObject(json); JSONArray arr = obj.optJSONArray("array"); List<String> list = new ArrayList<>(); for (int i = 0; i < arr.length(); i++) { list.add(arr.getString(i));//from w w w . j a va 2 s .c o m } return list; }
From source file:weathernotificationservice.wns.activities.MainActivity.java
public ParseResult parseLongTermJson(String result) { int i;/*from ww w .j av a 2s.com*/ 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.androidquery.simplefeed.fragments.FeedFragment.java
public void notiCb(String url, JSONObject jo, AjaxStatus status) { AQUtility.debug("noti", jo); if (jo != null) { int count = 0; PQuery aq = aq2.recycle(header); /*/*from ww w .j ava2s . co m*/ JSONObject sum = jo.optJSONObject("summary"); if(sum != null){ count = sum.optInt("unseen_count", 0); }*/ JSONArray ja = jo.optJSONArray("data"); for (int i = 0; i < ja.length(); i++) { JSONObject noti = ja.optJSONObject(i); if (noti.optInt("unread", 0) != 0) { count++; } } String message = count + " " + getString(R.string.n_notifications); aq.id(R.id.text_noti).text(message); int colorId = R.color.noti; int tf = Typeface.BOLD; if (count == 0) { colorId = R.color.grey; tf = Typeface.NORMAL; } aq.textColor(getResources().getColor(colorId)).getTextView().setTypeface(null, tf); } }
From source file:org.b3log.xiaov.service.TuringQueryService.java
/** * Chat with Turing Robot./*from ww w . j ava 2s .co 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 . j av a 2s. 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.funzio.pure2D.particles.nova.vo.GroupAnimatorVO.java
public GroupAnimatorVO(final JSONObject json) throws JSONException { super(json);//from ww w. j a v a 2 s .c om animators = NovaVO.getAnimators(json.optJSONArray("animators")); }
From source file:org.protorabbit.json.DefaultSerializer.java
@SuppressWarnings("unchecked") void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) { Object param = null;/*from w w w. j av a 2 s.com*/ Throwable ex = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().equals(name)) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length == 1 && jo.has(key)) { Class<?> tparam = paramTypes[0]; boolean allowNull = false; try { if (jo.isNull(key)) { // do nothing because param is already null : lets us not null on other types } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) { param = new Long(jo.getLong(key)); } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) { param = new Double(jo.getDouble(key)); } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) { param = new Integer(jo.getInt(key)); } else if (String.class.isAssignableFrom(tparam)) { param = jo.getString(key); } else if (Enum.class.isAssignableFrom(tparam)) { param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key)); } else if (Boolean.class.isAssignableFrom(tparam)) { param = new Boolean(jo.getBoolean(key)); } else if (jo.isNull(key)) { param = null; allowNull = true; } else if (Collection.class.isAssignableFrom(tparam)) { if (m.getGenericParameterTypes().length > 0) { Type t = m.getGenericParameterTypes()[0]; if (t instanceof ParameterizedType) { ParameterizedType tv = (ParameterizedType) t; if (tv.getActualTypeArguments().length > 0 && tv.getActualTypeArguments()[0] == String.class) { List<String> ls = new ArrayList<String>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { ls.add(ja.getString(j)); } } param = ls; } else if (tv.getActualTypeArguments().length == 1) { ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0]; Class itemClass = (Class) type.getRawType(); if (itemClass == Map.class && type.getActualTypeArguments().length == 2 && type.getActualTypeArguments()[0] == String.class && type.getActualTypeArguments()[1] == Object.class) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject mo = ja.getJSONObject(j); Iterator<String> keys = mo.keys(); while (keys.hasNext()) { String okey = keys.next(); Object ovalue = null; // make sure we don't get JSONObject$Null if (!mo.isNull(okey)) { ovalue = mo.get(okey); } map.put(okey, ovalue); } ls.add(map); } } param = ls; } else { getLogger().warning( "Don't know how to handle Collection of type : " + itemClass); } } else { getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0]); } } } } else { getLogger().warning( "Unable to serialize " + key + " : Don't know how to handle " + tparam); } } catch (JSONException e) { e.printStackTrace(); } if (param != null || allowNull) { try { if (m != null) { Object[] args = { param }; m.invoke(targetObject, args); ex = null; break; } } catch (SecurityException e) { ex = e; } catch (IllegalArgumentException e) { ex = e; } catch (IllegalAccessException e) { ex = e; } catch (InvocationTargetException e) { ex = e; } } } } } if (ex != null) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } }
From source file:com.vk.sdkweb.api.model.VKApiPhoto.java
/** * Fills a Photo instance from JSONObject. *///from w ww . j a v a 2 s . c o m public VKApiPhoto parse(JSONObject from) { album_id = from.optInt("album_id"); date = from.optLong("date"); height = from.optInt("height"); width = from.optInt("width"); owner_id = from.optInt("owner_id"); id = from.optInt("id"); text = from.optString("text"); access_key = from.optString("access_key"); photo_75 = from.optString("photo_75"); photo_130 = from.optString("photo_130"); photo_604 = from.optString("photo_604"); photo_807 = from.optString("photo_807"); photo_1280 = from.optString("photo_1280"); photo_2560 = from.optString("photo_2560"); JSONObject likes = from.optJSONObject("likes"); this.likes = ParseUtils.parseInt(likes, "count"); this.user_likes = ParseUtils.parseBoolean(likes, "user_likes"); comments = parseInt(from.optJSONObject("comments"), "count"); tags = parseInt(from.optJSONObject("tags"), "count"); can_comment = parseBoolean(from, "can_comment"); src.setOriginalDimension(width, height); JSONArray photo_sizes = from.optJSONArray("sizes"); if (photo_sizes != null) { src.fill(photo_sizes); } else { if (!TextUtils.isEmpty(photo_75)) { src.add(VKApiPhotoSize.create(photo_75, VKApiPhotoSize.S, width, height)); } if (!TextUtils.isEmpty(photo_130)) { src.add(VKApiPhotoSize.create(photo_130, VKApiPhotoSize.M, width, height)); } if (!TextUtils.isEmpty(photo_604)) { src.add(VKApiPhotoSize.create(photo_604, VKApiPhotoSize.X, width, height)); } if (!TextUtils.isEmpty(photo_807)) { src.add(VKApiPhotoSize.create(photo_807, VKApiPhotoSize.Y, width, height)); } if (!TextUtils.isEmpty(photo_1280)) { src.add(VKApiPhotoSize.create(photo_1280, VKApiPhotoSize.Z, width, height)); } if (!TextUtils.isEmpty(photo_2560)) { src.add(VKApiPhotoSize.create(photo_2560, VKApiPhotoSize.W, width, height)); } src.sort(); } return this; }