List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:com.tunyk.jsonbatchtranslate.JsonBatchTranslateDefaultImpl.java
private JSONObject iterateJSONObject(JSONObject json, String namespace, List<String> namespacesToInclude) throws JSONException { JSONObject res = new JSONObject(); Iterator itr = json.keys(); if (namespace == null) { namespace = ""; }//w ww. ja v a2 s.co m while (itr.hasNext()) { String key = (String) itr.next(); Object obj = json.get(key); String namespaceKey = namespace + "." + key; if (obj instanceof JSONObject) { JSONObject innerJson = iterateJSONObject((JSONObject) obj, namespaceKey, namespacesToInclude); res.put(key, innerJson); } else if (obj instanceof JSONArray) { JSONArray innerJson = iterateJSONArray((JSONArray) obj, namespaceKey, namespacesToInclude); res.put(key, innerJson); } else if ((obj instanceof String) && isNamespaceIncluded(namespaceKey, namespacesToInclude)) { Long id = getUID(); stringMap.put(id, obj.toString()); res.put(key, id); } else { res.put(key, obj); } } return res; }
From source file:com.tunyk.jsonbatchtranslate.JsonBatchTranslateDefaultImpl.java
private JSONObject reverseIterateJSONObject(JSONObject json) throws JSONException { JSONObject res = new JSONObject(); Iterator itr = json.keys(); while (itr.hasNext()) { String key = (String) itr.next(); Object obj = json.get(key); if (obj instanceof JSONObject) { JSONObject innerJson = reverseIterateJSONObject((JSONObject) obj); res.put(key, innerJson);//from w w w . j a va 2 s . com } else if (obj instanceof JSONArray) { JSONArray innerJson = reverseIterateJSONArray((JSONArray) obj); res.put(key, innerJson); } else if ((obj instanceof Long) && stringMap.containsKey(obj)) { res.put(key, stringMap.get(obj)); } else { res.put(key, obj); } } return res; }
From source file:com.ritboss.controller.AddProductServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.j a v a2s.co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html;charset=UTF-8"); String categoryUrl = request.getRequestURI().toString(); String prodCategory = categoryUrl.substring(categoryUrl.lastIndexOf("/") + 1); System.out.println("Product category is" + prodCategory); InputStreamReader in = new InputStreamReader(request.getInputStream()); BufferedReader bf = new BufferedReader(in); String line = bf.readLine(); JSONArray jsonArray = new JSONArray(line); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); Iterator keys = json.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = json.getString(key); System.out.println("key is: " + key + "Value is " + value); } } try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet AddProductServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet AddProductServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } catch (JSONException ex) { Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.soomla.levelup.LevelUp.java
private static boolean resetStateFromJSON(JSONObject state, String targetListName, IItemStateApplier stateApplier) { if (!state.has(targetListName)) { return true; }//from w w w .j a va 2s .co m SoomlaUtils.LogDebug(TAG, "Resetting state for " + targetListName); try { JSONObject itemsJSON = state.getJSONObject(targetListName); Iterator keysIter = itemsJSON.keys(); while (keysIter.hasNext()) { String itemId = (String) keysIter.next(); JSONObject itemValuesJSON = itemsJSON.getJSONObject(itemId); if (!stateApplier.applyState(itemId, itemValuesJSON)) { return false; } } } catch (JSONException e) { SoomlaUtils.LogError(TAG, "Unable to set state for " + targetListName + ". error: " + e.getLocalizedMessage()); return false; } return true; }
From source file:com.facebook.config.ConfigAccessor.java
public Map<String, String> getStringMap(String key) { return get(key, null, new Extractor<Map<String, String>>() { @Override//from w w w .ja v a 2s .co m public Map<String, String> extract(String key, JSONObject jsonObject) throws JSONException { Map<String, String> map = new HashMap<>(); JSONObject jsonMap = jsonObject.getJSONObject(key); ConfigAccessor mapAccessor = new ConfigAccessor(jsonMap); Iterator<String> keys = jsonMap.keys(); while (keys.hasNext()) { String mapKey = keys.next(); map.put(mapKey, mapAccessor.getString(mapKey)); } return map; } }); }
From source file:com.facebook.internal.ShareInternalUtilityTest.java
private boolean simpleJsonObjComparer(JSONObject obj1, JSONObject obj2) { if (obj1.names().length() != obj2.names().length()) { return false; }/*w ww .j av a2s . c om*/ Iterator<String> keys = obj1.keys(); while (keys.hasNext()) { try { String key = keys.next(); Object value1 = obj1.get(key); Object value2 = obj2.get(key); if (!jsonObjectValueComparer(value1, value2)) { return false; } } catch (Exception ex) { return false; } } return true; }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private void queryFileInfo(String lang, String title, FileInfo file) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("titles", title); params.put("prop", "imageinfo"); params.put("iiprop", "size"); try {//from w w w . ja va2 s.c o m String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageMap = response.getJSONObject("query").getJSONObject("pages"); JSONObject pageRecord = pageMap.getJSONObject((String) pageMap.keys().next()); if (pageRecord.has("imageinfo")) { JSONArray fileInfoList = pageRecord.getJSONArray("imageinfo"); file.setSize(fileInfoList.getJSONObject(0).getLong("size")); } else { file.setSize(0L); } } catch (JSONException ex) { LogHandler.log(this, LogLevel.WARN, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private List<Map<String, Object>> queryFileUsageWorker(String lang, String title, String cont) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("titles", title); params.put("prop", "fileusage"); params.put("fuprop", "pageid|title"); if (cont != null) { params.put("fucontinue", cont); }//from www .j av a 2s .c o m List<Map<String, Object>> result = new LinkedList<>(); try { String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageMap = response.getJSONObject("query").getJSONObject("pages"); JSONObject pageRecord = pageMap.getJSONObject((String) pageMap.keys().next()); if (pageRecord.has("fileusage")) { JSONArray pages = pageRecord.getJSONArray("fileusage"); for (int i = 0; i < pages.length(); i++) { Map<String, Object> record = new HashMap<>(); record.put("pageid", Long.toString(pages.getJSONObject(i).getLong("pageid"))); record.put("title", pages.getJSONObject(i).getString("title")); result.add(record); } } String queryContinue = null; if (response.has("query-continue")) { queryContinue = response.getJSONObject("query-continue").getJSONObject("fileusage") .getString("fucontinue"); } if (queryContinue != null) { List<Map<String, Object>> moreResult = queryFileUsageWorker(lang, title, queryContinue); result.addAll(moreResult); } } catch (Exception ex) { LogHandler.log(this, LogLevel.WARN, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } return result; }
From source file:com.soomla.store.domain.data.VirtualCurrencyPack.java
/** * Converts the current {@link VirtualCurrencyPack} to a JSONObject. * @return a JSONObject representation of the current {@link VirtualCurrencyPack}. */// w w w .j a v a2 s.com public JSONObject toJSONObject() { JSONObject parentJsonObject = super.toJSONObject(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put(JSONConsts.CURRENCYPACK_PRICE, new Double(mPrice)); jsonObject.put(JSONConsts.CURRENCYPACK_PRODUCT_ID, mGoogleItem.getMarketId()); jsonObject.put(JSONConsts.CURRENCYPACK_AMOUNT, new Integer(mCurrencyAmount)); jsonObject.put(JSONConsts.CURRENCYPACK_CURRENCYITEMID, mCurrency.getItemId()); Iterator<?> keys = parentJsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); jsonObject.put(key, parentJsonObject.get(key)); } } catch (JSONException e) { if (StoreConfig.debug) { Log.d(TAG, "An error occured while generating JSON object."); } } return jsonObject; }
From source file:com.android.i18n.addressinput.JsoMap.java
/** * Retrieve the JsoMap object for specified key. * * @param key key name./* w w w . java2s .c o m*/ * @return JsoMap object. * @throws ClassCastException, IllegalArgumentException. */ @SuppressWarnings("unchecked") // JSONObject.keys() has no type information. JsoMap getObj(String key) throws ClassCastException, IllegalArgumentException { try { Object o = super.get(key); if (o instanceof JSONObject) { JSONObject value = (JSONObject) o; ArrayList<String> keys = new ArrayList<String>(value.length()); for (Iterator<String> it = value.keys(); it.hasNext();) { keys.add(it.next()); } String[] names = new String[keys.size()]; return new JsoMap(value, keys.toArray(names)); } else if (o instanceof Integer) { throw new IllegalArgumentException(); } else { throw new ClassCastException(); } } catch (JSONException e) { return null; } }