List of usage examples for org.json JSONObject isNull
public boolean isNull(String key)
From source file:menusearch.json.JSONProcessor.java
/** *//from ww w.j a v a2s . com * @param JSON string: requires the JSON string of the parameters the user enter for the search * @return RecipeSummaryList: a RecipeSummaryList where it contains information about the recipes that matches the search the user made * @throws java.io.IOException */ public static RecipeSummaryList parseRecipeMatches(String results) throws IOException { CourseList courseList = new CourseList(); RecipeSummaryList list = new RecipeSummaryList(); JSONTokener tokenizer = new JSONTokener(results); JSONObject resultList = new JSONObject(tokenizer); JSONArray matches = resultList.getJSONArray("matches"); for (int i = 0; i < matches.length(); i++) { RecipeSummary r = new RecipeSummary(); JSONObject currentRecipe = matches.getJSONObject(i); JSONObject imageUrls = currentRecipe.getJSONObject("imageUrlsBySize"); String link = "90"; String number = imageUrls.getString(link); r.setImageUrlsBySize(number); String source = (String) currentRecipe.getString("sourceDisplayName"); r.setSourceDisplayName(source); JSONArray listOfIngredients = currentRecipe.getJSONArray("ingredients"); for (int n = 0; n < listOfIngredients.length(); n++) { String currentIngredients = listOfIngredients.getString(n); r.ingredients.add(currentIngredients); } String id = (String) currentRecipe.getString("id"); r.setId(id); String recipe = (String) currentRecipe.get("recipeName"); r.setRecipeName(recipe); JSONArray smallImage = currentRecipe.getJSONArray("smallImageUrls"); for (int l = 0; l < smallImage.length(); l++) { String currentUrl = (String) smallImage.get(l); r.setSmallImageUrls(currentUrl); } int timeInSeconds = (int) currentRecipe.getInt("totalTimeInSeconds"); r.setTotalTimeInSeconds(timeInSeconds); String a = "attributes"; String c = "course"; if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has(c)) { for (int j = 0; j < currentAttributes.getJSONArray(c).length(); j++) { String course = currentAttributes.getJSONArray(c).getString(j); courseList.add(course); } r.setCourses(courseList); } } CuisineList cuisineList = new CuisineList(); if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has("cuisine")) { for (int j = 0; j < currentAttributes.getJSONArray("cuisine").length(); j++) { String currentCuisine = currentAttributes.getJSONArray("cuisine").getString(j); cuisineList.add(currentCuisine); } r.setCusines(cuisineList); } } String f = "flavors"; JSONObject currentFlavors; if (currentRecipe.has(f) == true) { if (currentRecipe.isNull(f) == false) { currentFlavors = currentRecipe.getJSONObject(f); double saltyRating = currentFlavors.getDouble("salty"); double sourRating = currentFlavors.getDouble("sour"); double sweetRating = currentFlavors.getDouble("sweet"); double bitterRating = currentFlavors.getDouble("bitter"); double meatyRating = currentFlavors.getDouble("meaty"); double piguantRating = currentFlavors.getDouble("piquant"); r.flavors.setSalty(saltyRating); r.flavors.setSour(sourRating); r.flavors.setSweet(sweetRating); r.flavors.setBitter(bitterRating); r.flavors.setMeaty(meatyRating); r.flavors.setPiquant(piguantRating); } if (currentRecipe.get(f) == null) { r.flavors = null; } if (currentRecipe.get(f) == null) r.flavors = null; } double rate = currentRecipe.getInt("rating"); r.setRating(rate); list.matches.add(i, r); } return list; }
From source file:me.mast3rplan.phantombot.cache.UsernameCache.java
public String resolve(String username, Map<String, String> tags) { String lusername = username.toLowerCase(); if (cache.containsKey(lusername)) { return cache.get(lusername); } else {// w ww . j a v a2s . co m if (tags.containsKey("display-name") && tags.get("display-name").equalsIgnoreCase(lusername)) { cache.put(lusername, tags.get("display-name")); if (PhantomBot.enableDebugging) { com.gmt2001.Console.out .println(">>UsernameCache detected using v3: " + tags.get("display-name")); } return tags.get("display-name"); } if (username.equalsIgnoreCase("jtv") || username.equalsIgnoreCase("twitchnotify") || new Date().before(timeoutExpire)) { return username; } try { JSONObject user = TwitchAPIv3.instance().GetUser(lusername); if (user.getBoolean("_success")) { if (user.getInt("_http") == 200) { String displayName = user.getString("display_name"); cache.put(lusername, displayName); return displayName; } else { try { throw new Exception("[HTTPErrorException] HTTP " + user.getInt("status") + " " + user.getString("error") + ". req=" + user.getString("_type") + " " + user.getString("_url") + " " + user.getString("_post") + " " + (user.has("message") && !user.isNull("message") ? "message=" + user.getString("message") : "content=" + user.getString("_content"))); } catch (Exception e) { com.gmt2001.Console.out.println( "UsernameCache.updateCache>>Failed to get username: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); return username; } } } else { if (user.getString("_exception").equalsIgnoreCase("SocketTimeoutException") || user.getString("_exception").equalsIgnoreCase("IOException")) { Calendar c = Calendar.getInstance(); if (lastFail.after(new Date())) { numfail++; } else { numfail = 1; } c.add(Calendar.MINUTE, 1); lastFail = c.getTime(); if (numfail >= 5) { timeoutExpire = c.getTime(); } } return username; } } catch (Exception e) { com.gmt2001.Console.err.printStackTrace(e); return username; } } }
From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java
private LocationResult parsePlace(JSONObject place) throws JSONException { LocationResult result = new LocationResult(); JSONObject country = place.getJSONObject("country"); result.id = place.getString("woeid"); result.country = country.getString("content"); result.countryId = country.getString("code"); if (!place.isNull("postal")) { result.postal = place.getJSONObject("postal").getString("content"); }/*from ww w .ja v a 2 s. c om*/ for (String name : LOCALITY_NAMES) { if (!place.isNull(name)) { result.city = place.getJSONObject(name).getString("content"); break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "JSON data " + place.toString() + " -> id=" + result.id + ", city=" + result.city + ", country=" + result.countryId); } if (result.id == null || result.city == null || result.countryId == null) { return null; } return result; }
From source file:edu.mit.mobile.android.locast.data.JsonSyncableItem.java
/** * Given a JSON item and a sync map, create a ContentValues map to be inserted into the DB. * * @param context/*from w w w. j ava 2s.c om*/ * @param localItem will be null if item is new to mobile. If it's been sync'd before, will point to local entry. * @param item incoming JSON item. * @param mySyncMap A mapping between the JSON object and the content values. * @return new ContentValues, ready to be inserted into the database. * @throws JSONException * @throws IOException * @throws NetworkProtocolException */ public final static ContentValues fromJSON(Context context, Uri localItem, JSONObject item, SyncMap mySyncMap) throws JSONException, IOException, NetworkProtocolException { final ContentValues cv = new ContentValues(); for (final String propName : mySyncMap.keySet()) { final SyncItem map = mySyncMap.get(propName); if (!map.isDirection(SyncItem.SYNC_FROM)) { continue; } if (map.isOptional() && (!item.has(map.remoteKey) || item.isNull(map.remoteKey))) { continue; } final ContentValues cv2 = map.fromJSON(context, localItem, item, propName); if (cv2 != null) { cv.putAll(cv2); } } return cv; }
From source file:ca.nrc.cadc.xml.JsonInputter.java
public Document input(final String json) throws JSONException { JSONObject rootJson = new JSONObject(json); List<String> keys = Arrays.asList(JSONObject.getNames(rootJson)); List<Namespace> namespaces = new ArrayList<Namespace>(); Namespace namespace = getNamespace(namespaces, rootJson, keys); String rootKey = null;/*from ww w.j a v a2 s .c o m*/ List<Attribute> attributes = new ArrayList<Attribute>(); for (String key : keys) { if (!key.startsWith("@xmlns")) { if (key.startsWith("@")) { String value; if (rootJson.isNull(key)) { value = ""; } else { value = getStringValue(rootJson.get(key)); } attributes.add(new Attribute(key.substring(1), value)); } else { // DOM can only have one root element. if (rootKey != null) { throw new IllegalStateException("Found multiple root entries"); } rootKey = key; } } } Element rootElement = new Element(rootKey, namespace); for (Attribute attribute : attributes) { rootElement.setAttribute(attribute); } Object value = rootJson.get(rootKey); processObject(rootKey, value, rootElement, namespace, namespaces); Document document = new Document(); document.setRootElement(rootElement); return document; }
From source file:ca.nrc.cadc.xml.JsonInputter.java
private void processJSONObject(JSONObject jsonObject, Element element, List<Namespace> namespaces) throws JSONException { List<String> keys = Arrays.asList(JSONObject.getNames(jsonObject)); Namespace namespace = getNamespace(namespaces, jsonObject, keys); if (namespace == null) { namespace = element.getNamespace(); }/* w w w . ja v a 2 s .co m*/ for (String key : keys) { if (jsonObject.isNull(key)) { continue; } // attribute if (key.startsWith("@")) { Object value = jsonObject.get(key); element.setAttribute(new Attribute(key.substring(1), getStringValue(value))); continue; } // text content Object value = jsonObject.get(key); if (key.equals("$")) { element.setText(getStringValue(value)); continue; } Element child = new Element(key, namespace); if (listElementMap.containsKey(key)) { final String childKey = listElementMap.get(key); final Object childObject = ((JSONObject) value).get("$"); Element grandChild = new Element(childKey, namespace); if (childObject instanceof JSONArray) { processJSONArray(key, (JSONArray) childObject, child, namespace, namespaces); } else if (childObject instanceof JSONObject) { processJSONObject((JSONObject) childObject, grandChild, namespaces); child.addContent(grandChild); } } else if (value instanceof JSONObject) { processJSONObject((JSONObject) value, child, namespaces); } element.addContent(child); } }
From source file:ca.nrc.cadc.xml.JsonInputter.java
private Namespace getNamespace(List<Namespace> namespaces, JSONObject jsonObject, List<String> keys) throws JSONException { for (String key : keys) { if (key.equals("@xmlns")) { if (jsonObject.isNull(key)) { break; }/*w ww . j av a 2s . c om*/ String uri = jsonObject.getString(key); Namespace namespace = Namespace.getNamespace(uri); if (!namespaces.contains(namespace)) { namespaces.add(namespace); } return namespace; } } return null; }
From source file:edu.wpi.margrave.SQSReader.java
protected static void handleSQSStatement(JSONObject thisStatement, MPolicyLeaf result, int counter) throws JSONException, MGEUnsupportedSQS, MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {//from ww w. jav a2 s.c o m String ruleId = result.name + "_rule_" + counter; // Documentation says the statement ID is optional. if (!thisStatement.isNull("Sid")) ruleId = thisStatement.getString("Sid"); String effect; if (!thisStatement.isNull("Effect")) effect = thisStatement.getString("Effect"); else return; // no effect means no need to add the rule List<String> ruleNameOrdering = new ArrayList<String>(4); ruleNameOrdering.add("p"); ruleNameOrdering.add("a"); ruleNameOrdering.add("r"); ruleNameOrdering.add("c"); Formula theTarget = Formula.TRUE; Formula theCondition = Formula.TRUE; // target starts as true. All criteria must be met, so just "and" each on. // ************************* // "Principal": disjunction if (thisStatement.isNull("Principal")) return; // never applies, so don't create the rule. theTarget = handleStatementPAR(thisStatement.get("Principal"), "p", "Principal", theTarget, result.vocab, "Principal"); // ************************* // "Action": disjunction if (thisStatement.isNull("Action")) return; // never applies, so don't create the rule. theTarget = handleStatementPAR(thisStatement.get("Action"), "a", "Action", theTarget, result.vocab, "Action"); // ************************* // "Resource": disjunction if (thisStatement.isNull("Resource")) return; // never applies, so don't create the rule. theTarget = handleStatementPAR(thisStatement.get("Resource"), "r", "Resource", theTarget, result.vocab, "Resource"); // ************************* // "Condition": more complex // Condition optional? TODO -- for now if no condition, just finalize the rule. // (Why are P/A/R special?) if (!thisStatement.isNull("Condition")) theCondition = handleStatementCondition(thisStatement.getJSONObject("Condition"), theTarget, result.vocab); // Finalize the rule. result.addRule(ruleId, effect, ruleNameOrdering, theTarget, theCondition); }
From source file:com.macmoim.pang.FoodListFragment.java
/** * Parsing json reponse and passing the data to feed view list adapter *//*from ww w . j a v a 2 s .co m*/ private void ParseJsonFeed(JSONObject response, boolean toClearArray) { if (mRecyclerView == null) { return; } if (toClearArray) { feedItems.clear(); } try { if ("success".equals(response.getString("ret_val"))) { JSONArray feedArray = response.getJSONArray("post_info"); int length = feedArray.length(); for (int i = 0; i < length; i++) { JSONObject feedObj = (JSONObject) feedArray.get(i); FoodItem item = new FoodItem(); item.setId(feedObj.getInt("id")); item.setName(feedObj.getString("title")); item.setUserId(feedObj.getString("user_id")); item.setUserName(feedObj.getString("user_name")); // Image might be null sometimes String image = feedObj.isNull("img_path") ? null : feedObj.getString("img_path"); item.setImge(image); item.setTimeStamp(feedObj.getString("date")); item.setLikeSum(feedObj.getString("like_sum")); String score = feedObj.getString("score"); item.setScore("null".equals(score) ? "0" : score); Log.d(TAG, "parseJsonFeed dbname " + feedObj.getString("img_path")); feedItems.add(0, item); } // notify data changes to list adapater mRecyclerView.getAdapter().notifyDataSetChanged(); } else { Log.e(TAG, "return fail : " + response.getString("ret_detail")); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:me.mast3rplan.phantombot.cache.FollowersCache.java
public int quickUpdate(String channel) throws Exception { JSONObject j = TwitchAPIv3.instance().GetChannelFollows(channel, 100, 0, false); if (j.getBoolean("_success")) { if (j.getInt("_http") == 200) { int i = j.getInt("_total"); Map<String, JSONObject> newCache = Maps.newHashMap(); JSONArray followers = j.getJSONArray("follows"); for (int b = 0; b < followers.length(); b++) { JSONObject follower = followers.getJSONObject(b); newCache.put(follower.getJSONObject("user").getString("name"), follower); }/*w ww .j a v a2 s . co m*/ for (String key : newCache.keySet()) { if (cache == null || !cache.containsKey(key)) { cache.put(key, newCache.get(key)); EventBus.instance().post( new TwitchFollowEvent(key, PhantomBot.instance().getChannel("#" + this.channel))); } } this.count = cache.size(); return i; } else { throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " " + j.getString("error") + ". req=" + j.getString("_type") + " " + j.getString("_url") + " " + j.getString("_post") + " " + (j.has("message") && !j.isNull("message") ? "message=" + j.getString("message") : "content=" + j.getString("_content"))); } } else { throw new Exception("[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage")); } }