List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:com.nextgis.maplib.map.VectorLayer.java
public String createFromGeoJSON(JSONObject geoJSONObject) { try {//from www. ja v a 2 s. c om //check crs boolean isWGS84 = true; //if no crs tag - WGS84 CRS if (geoJSONObject.has(GEOJSON_CRS)) { JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS); //the link is unsupported yet. if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) { return mContext.getString(R.string.error_crs_unsuported); } JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES); String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME); if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84 isWGS84 = true; } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator isWGS84 = false; } else { return mContext.getString(R.string.error_crs_unsuported); } } //load contents to memory and reproject if needed JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES); if (0 == geoJSONFeatures.length()) { return mContext.getString(R.string.error_empty_dataset); } List<Feature> features = new ArrayList<>(); List<Pair<String, Integer>> fields = new ArrayList<>(); int geometryType = GTNone; for (int i = 0; i < geoJSONFeatures.length(); i++) { JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i); //get geometry JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY); GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry); if (geometryType == GTNone) { geometryType = geometry.getType(); } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) { //skip different geometry type continue; } //reproject if needed if (isWGS84) { geometry.setCRS(CRS_WGS84); geometry.project(CRS_WEB_MERCATOR); } else { geometry.setCRS(CRS_WEB_MERCATOR); } int nId = i; if (jsonFeature.has(GEOJSON_ID)) nId = jsonFeature.getInt(GEOJSON_ID); Feature feature = new Feature(nId, fields); // ID == i feature.setGeometry(geometry); //normalize attributes JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES); Iterator<String> iter = jsonAttributes.keys(); while (iter.hasNext()) { String key = iter.next(); Object value = jsonAttributes.get(key); int nType = NOT_FOUND; //check type if (value instanceof Integer || value instanceof Long) { nType = FTInteger; } else if (value instanceof Double || value instanceof Float) { nType = FTReal; } else if (value instanceof Date) { nType = FTDateTime; } else if (value instanceof String) { nType = FTString; } else if (value instanceof JSONObject) { nType = NOT_FOUND; //the some list - need to check it type FTIntegerList, FTRealList, FTStringList } if (nType != NOT_FOUND) { int fieldIndex = NOT_FOUND; for (int j = 0; j < fields.size(); j++) { if (fields.get(j).first.equals(key)) { fieldIndex = j; } } if (fieldIndex == NOT_FOUND) { //add new field Pair<String, Integer> fieldKey = Pair.create(key, nType); fieldIndex = fields.size(); fields.add(fieldKey); } feature.setFieldValue(fieldIndex, value); } } features.add(feature); } String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB"; for (int i = 0; i < fields.size(); ++i) { Pair<String, Integer> field = fields.get(i); tableCreate += ", " + field.first + " "; switch (field.second) { case FTString: tableCreate += "TEXT"; break; case FTInteger: tableCreate += "INTEGER"; break; case FTReal: tableCreate += "REAL"; break; case FTDateTime: tableCreate += "TIMESTAMP"; break; } } tableCreate += " );"; GeoEnvelope extents = new GeoEnvelope(); for (Feature feature : features) { //update bbox extents.merge(feature.getGeometry().getEnvelope()); } //1. create table and populate with values MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance(); SQLiteDatabase db = map.getDatabase(true); db.execSQL(tableCreate); for (Feature feature : features) { ContentValues values = new ContentValues(); values.put("_ID", feature.getId()); try { values.put("GEOM", feature.getGeometry().toBlob()); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < fields.size(); ++i) { if (!feature.isValuePresent(i)) continue; switch (fields.get(i).second) { case FTString: values.put(fields.get(i).first, feature.getFieldValueAsString(i)); break; case FTInteger: values.put(fields.get(i).first, (int) feature.getFieldValue(i)); break; case FTReal: values.put(fields.get(i).first, (double) feature.getFieldValue(i)); break; case FTDateTime: values.put(fields.get(i).first, feature.getFieldValueAsString(i)); break; } } db.insert(mPath.getName(), "", values); } //2. save the layer properties to config.json mGeometryType = geometryType; mExtents = extents; mIsInitialized = true; setDefaultRenderer(); save(); //3. fill the geometry and labels array mVectorCacheItems = new ArrayList<>(); for (Feature feature : features) { mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId())); } if (null != mParent) { //notify the load is over LayerGroup layerGroup = (LayerGroup) mParent; layerGroup.onLayerChanged(this); } return ""; } catch (JSONException e) { e.printStackTrace(); return e.getLocalizedMessage(); } }
From source file:org.loklak.api.iot.NOAAAlertServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;/*w ww . ja v a 2 s. c o m*/ } String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml"))); try { // Conversion of the XML Layers through PERL into the required JSON for well structured XML /* <resources> <string-array name="preference_county_entries_us"> <item>Entire Country</item> </string-array> <string-array name="preference_county_entryvalues_us"> <item>https://alerts.weather.gov/cap/us.php?x=0</item> </string-array> . . . Similarly every 2 DOM elements together in <resources> constitute a pair. </resources> */ JSONObject json = XML.toJSONObject(content); PrintWriter sos = response.getWriter(); JSONObject resourceObject = json.getJSONObject("resources"); JSONArray stringArray = resourceObject.getJSONArray("string-array"); JSONObject result = new JSONObject(true); // Extract and map the itemname and the url strings /* { "item": "Entire Country", "name": "preference_county_entries_us" }, { "item": "https://alerts.weather.gov/cap/us.php?x=0", "name": "preference_county_entryvalues_us" } */ for (int i = 0; i < stringArray.length(); i += 2) { JSONObject keyJSONObject = stringArray.getJSONObject(i); JSONObject valueJSONObject = stringArray.getJSONObject(i + 1); Object kItemObj = keyJSONObject.get("item"); Object vItemObj = valueJSONObject.get("item"); // Since instances are variable, we need to check if they're Arrays or Strings // The processing for the Key : Value mappings will change for each type of instance if (kItemObj instanceof JSONArray) { if (vItemObj instanceof JSONArray) { JSONArray kArray = keyJSONObject.getJSONArray("item"); JSONArray vArray = valueJSONObject.getJSONArray("item"); for (int location = 0; location < kArray.length(); location++) { String kValue = kArray.getString(location); String vValue = vArray.getString(location); result.put(kValue, vValue); } } } else { // They are plain strings String kItemValue = keyJSONObject.getString("item"); String vItemValue = valueJSONObject.getString("item"); result.put(kItemValue, vItemValue); } } // Sample response in result has to be something like /* { "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0", "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0", "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0", "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0", "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0", "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0", . . . And so on. } */ sos.print(result.toString(2)); sos.println(); } catch (IOException e) { Log.getLog().warn(e); JSONObject json = new JSONObject(true); json.put("error", "Looks like there is an error in the conversion"); json.put("type", "Error"); PrintWriter sos = response.getWriter(); sos.print(json.toString(2)); sos.println(); } }
From source file:com.facebook.share.ShareApi.java
private static void putImageInBundleWithArrayFormat(Bundle parameters, int index, JSONObject image) throws JSONException { Iterator<String> keys = image.keys(); while (keys.hasNext()) { String property = keys.next(); String key = String.format(Locale.ROOT, "image[%d][%s]", index, property); parameters.putString(key, image.get(property).toString()); }/* w w w . j av a 2 s. co m*/ }
From source file:wowhead_itemreader.WoWHeadData.java
private String getJsonValue(JSONObject object, String key) { try {// w w w . j ava 2 s .c o m return object.get(key).toString(); } catch (JSONException ex) { } return null; }
From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java
/** * get next page url/*from ww w. j a va 2s. c o m*/ * * @param object * @return * @throws Exception */ private String getNextPageURL(JSONObject object) throws Exception { JSONObject paging = (JSONObject) object.get("paging"); return (String) paging.get("next"); }
From source file:io.v.positioning.BluetoothProximityServlet.java
/** * Processes a POST request to save nearby devices scanned using Bluetooth * * @param req The servlet request that includes JSONObject with properties to be saved * @param resp The servlet response informing a user if the request was successful or not *///from w w w . j av a2 s . c o m @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); BufferedReader br = req.getReader(); try { JSONObject jo = new JSONObject(br.readLine()); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity("bluetooth"); entity.setProperty("androidId", jo.get("androidId")); entity.setProperty("myMacAddress", jo.get("myMacAddress")); entity.setProperty("remoteName", jo.get("remoteName")); entity.setProperty("remoteAddress", jo.get("remoteAddress")); entity.setProperty("remoteRssi", jo.get("remoteRssi")); entity.setProperty("deviceTime", jo.get("deviceTime")); entity.setProperty("serverTime", System.currentTimeMillis()); datastore.put(entity); resp.getWriter().println("New bluetooth device added."); } catch (Exception e) { resp.getWriter().println("Recording failed. " + e); } }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
private void addActionRef(JSONObject json) { HobsonActionRef ref = new HobsonActionRef(json.getString("pluginId"), json.getString("actionId"), json.getString("name")); if (json.has("properties")) { JSONObject propJson = json.getJSONObject("properties"); Iterator it = propJson.keys(); while (it.hasNext()) { String key = (String) it.next(); ref.addProperty(key, propJson.get(key)); }//from ww w . j a v a 2 s. com } actions.add(ref); }
From source file:ai.susi.mind.SusiSkill.java
/** * Generate a set of skills from a single skill definition. This may be possible if the skill contains an 'options' * object which creates a set of skills, one for each option. The options combine with one set of phrases * @param json - a multi-skill definition * @return a set of skills//w w w . ja va2 s . co m */ public static List<SusiSkill> getSkills(JSONObject json) { if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); final List<SusiSkill> skills = new ArrayList<>(); if (json.has("options")) { JSONArray options = json.getJSONArray("options"); for (int i = 0; i < options.length(); i++) { JSONObject option = new JSONObject(); option.put("phrases", json.get("phrases")); JSONObject or = options.getJSONObject(i); for (String k : or.keySet()) option.put(k, or.get(k)); skills.add(new SusiSkill(option)); } } else { try { SusiSkill skill = new SusiSkill(json); skills.add(skill); } catch (PatternSyntaxException e) { Logger.getLogger("SusiSkill") .warning("Regular Expression error in Susi Skill: " + json.toString(2)); } } return skills; }
From source file:com.alvexcore.share.ShareExtensionRegistry.java
protected void getEditionFromRepo() { try {/*from w w w .j a va 2 s . co m*/ // Get connector RequestContext rc = ThreadLocalRequestContext.getRequestContext(); String userId = rc.getUserId(); Connector conn = rc.getServiceRegistry().getConnectorService().getConnector("alfresco"); String url = "/api/alvex/server"; Response response = conn.call(url); if (Status.STATUS_OK == response.getStatus().getCode()) { org.json.JSONObject scriptResponse = new org.json.JSONObject(response.getResponse()); edition = (String) scriptResponse.get(JSON_PROP_EDITION); } } catch (Exception e) { edition = EDITION_CE; } }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static JSONArray addRepeatedNodeToJson(Element container, Repeat f, String permlevel, JSONObject tempSon) throws JSONException { JSONArray node = new JSONArray(); List<FieldSet> children = getChildrenWithGroupFields(f, permlevel); JSONArray elementlist = extractRepeatData(container, f, permlevel); JSONObject siblingitem = new JSONObject(); for (int i = 0; i < elementlist.length(); i++) { JSONObject element = elementlist.getJSONObject(i); Iterator<?> rit = element.keys(); while (rit.hasNext()) { String key = (String) rit.next(); JSONArray arrvalue = new JSONArray(); for (FieldSet fs : children) { if (fs instanceof Repeat && ((Repeat) fs).hasServicesParent()) { if (!((Repeat) fs).getServicesParent()[0].equals(key)) { continue; }/*from w ww. j av a2 s . c o m*/ Object value = element.get(key); arrvalue = (JSONArray) value; } else { if (!fs.getID().equals(key)) { continue; } Object value = element.get(key); arrvalue = (JSONArray) value; } if (fs instanceof Field) { for (int j = 0; j < arrvalue.length(); j++) { JSONObject repeatitem = new JSONObject(); //XXX remove when service layer supports primary tags if (f.hasPrimary() && j == 0) { repeatitem.put("_primary", true); } Element child = (Element) arrvalue.get(j); Object val = child.getText(); Field field = (Field) fs; String id = field.getID(); if (f.asSibling()) { addExtraToJson(siblingitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { siblingitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { siblingitem.put(id, val); } } else { addExtraToJson(repeatitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { repeatitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { repeatitem.put(id, val); } node.put(repeatitem); } tempSon = addtemp(tempSon, fs.getID(), child.getText()); } } else if (fs instanceof Group) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Group rp = (Group) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { JSONArray a1 = tout.getJSONArray(rp.getID()); JSONObject o1 = a1.getJSONObject(0); siblingitem.put(fs.getID(), o1); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } else if (fs instanceof Repeat) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Repeat rp = (Repeat) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID())); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } } } } if (f.asSibling()) { node.put(siblingitem); } return node; }