List of usage examples for org.json JSONObject toString
public String toString(int indentFactor) throws JSONException
From source file:com.facebook.android.UploadPhotoResultDialog.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new Handler(); setContentView(R.layout.upload_photo_response); LayoutParams params = getWindow().getAttributes(); params.width = LayoutParams.FILL_PARENT; params.height = LayoutParams.FILL_PARENT; getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); mOutput = (TextView) findViewById(R.id.apiOutput); mUsefulTip = (TextView) findViewById(R.id.usefulTip); mViewPhotoButton = (Button) findViewById(R.id.view_photo_button); mTagPhotoButton = (Button) findViewById(R.id.tag_photo_button); mUploadedPhoto = (ImageView) findViewById(R.id.uploadedPhoto); JSONObject json; try {//from w w w.j a v a2s .com json = Util.parseJson(response); final String photo_id = json.getString("id"); this.photo_id = photo_id; mOutput.setText(json.toString(2)); mUsefulTip.setText(activity.getString(R.string.photo_tip)); Linkify.addLinks(mUsefulTip, Linkify.WEB_URLS); mViewPhotoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (hidePhoto) { mViewPhotoButton.setText(R.string.view_photo); hidePhoto = false; mUploadedPhoto.setImageBitmap(null); } else { hidePhoto = true; mViewPhotoButton.setText(R.string.hide_photo); /* * Source tag: view_photo_tag */ Bundle params = new Bundle(); params.putString("fields", "picture"); dialog = ProgressDialog.show(activity, "", activity.getString(R.string.please_wait), true, true); dialog.show(); Utility.mAsyncRunner.request(photo_id, params, new ViewPhotoRequestListener()); } } }); mTagPhotoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* * Source tag: tag_photo_tag */ setTag(); } }); } catch (JSONException e) { setText(activity.getString(R.string.exception) + e.getMessage()); } catch (FacebookError e) { setText(activity.getString(R.string.facebook_error) + e.getMessage()); } }
From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java
private void generateAndSendGeoJsonToolReport() { FiskInfoUtility fiskInfoUtility = new FiskInfoUtility(); JSONObject featureCollection = new JSONObject(); try {//from www.j a v a 2 s . co m Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet(); JSONArray featureList = new JSONArray(); for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) { for (final ToolEntry toolEntry : dateEntry.getValue()) { if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) { continue; } toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED : ToolEntryStatus.STATUS_SENT_UNCONFIRMED); JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker); featureList.put(gjsonTool); } } if (featureList.length() == 0) { Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show(); return; } user.writeToSharedPref(getActivity()); featureCollection.put("features", featureList); featureCollection.put("type", "FeatureCollection"); featureCollection.put("crs", JSONObject.NULL); featureCollection.put("bbox", JSONObject.NULL); String toolString = featureCollection.toString(4); if (fiskInfoUtility.isExternalStorageWritable()) { fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(), getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false); String directoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); String fileName = directoryPath + "/FiskInfo/api_setting.json"; File apiSettingsFile = new File(fileName); String recipient = null; if (apiSettingsFile.exists()) { InputStream inputStream; InputStreamReader streamReader; JsonReader jsonReader; try { inputStream = new BufferedInputStream(new FileInputStream(apiSettingsFile)); streamReader = new InputStreamReader(inputStream, "UTF-8"); jsonReader = new JsonReader(streamReader); jsonReader.beginObject(); while (jsonReader.hasNext()) { String name = jsonReader.nextName(); if (name.equals("email")) { recipient = jsonReader.nextString(); } else { jsonReader.skipValue(); } } jsonReader.endObject(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } } recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient; String[] recipients = new String[] { recipient }; Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/plain"); String toolIds; StringBuilder sb = new StringBuilder(); sb.append("Redskapskoder:\n"); for (int i = 0; i < featureList.length(); i++) { sb.append(Integer.toString(i + 1)); sb.append(": "); sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId")); sb.append("\n"); } toolIds = sb.toString(); intent.putExtra(Intent.EXTRA_EMAIL, recipients); intent.putExtra(Intent.EXTRA_TEXT, toolIds); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header)); File file = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/FiskInfo/Redskapsrapport.geojson"); Uri uri = Uri.fromFile(file); intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header))); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:org.mapsforge.directions.TurnByTurnDescriptionToString.java
/** * Generates a GeoJSON String which represents the route * /*from w w w. j a v a 2s .c o m*/ * @return a string containing a GeoJSON representation of the route * @throws JSONException * if the construction of the JSON fails */ public String toJSONString() throws JSONException { JSONObject json = new JSONObject(); JSONArray jsonfeatures = new JSONArray(); json.put("type", "FeatureCollection"); json.put("features", jsonfeatures); for (TurnByTurnStreet street : streets) { JSONObject jsonstreet = new JSONObject(); jsonstreet.put("type", "Feature"); JSONArray streetCoordinatesAsJson = new JSONArray(); for (int j = 0; j < street.points.size(); j++) { GeoCoordinate sc = street.points.elementAt(j); streetCoordinatesAsJson.put(new JSONArray().put(sc.getLongitude()).put(sc.getLatitude())); } jsonstreet.put("geometry", new JSONObject().put("type", "LineString").put("coordinates", streetCoordinatesAsJson)); jsonstreet.put("properties", new JSONObject().put("Name", street.name).put("Ref", street.ref).put("Length", street.length) .put("Angle", street.angleFromStreetLastStreet).put("Directions", street.turnByTurnText) .put("Type", street.type)); jsonfeatures.put(jsonstreet); } return json.toString(2); }
From source file:com.comcast.cmb.common.controller.EndpointServlet.java
private String formatMessage(String str) { //Escape the "<" and ">" characters String fmtMsg = str.replace("<", "<"); fmtMsg = fmtMsg.replace(">", ">"); //pretty print json try {/*from www . j av a2s. c om*/ JSONObject json = new JSONObject(fmtMsg); fmtMsg = json.toString(2); } catch (Exception ex) { //not a json string } return fmtMsg; }
From source file:com.kevinquan.android.utils.JSONUtils.java
/** * Returns a "pretty print" string version of the JSONObject * @param obj The object to pretty print * @param indentation The amount of indentation for each level * @return A pretty string /*from w w w . ja v a 2 s . co m*/ */ public static String prettyPrint(JSONObject obj, int indentation) { if (obj == null) { return new String(); } try { return obj.toString(indentation); } catch (JSONException je) { Log.w(TAG, "Could not pretty print JSON: " + obj.toString()); return new String(); } }
From source file:pt.webdetails.cfr.CfrContentGenerator.java
@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON) public void setPermissions(OutputStream out) throws JSONException, IOException { String path = checkRelativePathSanity(getRequestParameters().getStringParameter(pathParameterPath, null)); String[] userOrGroupId = getRequestParameters().getStringArrayParameter(pathParameterGroupOrUserId, new String[] {}); String[] _permissions = getRequestParameters().getStringArrayParameter(pathParameterPermission, new String[] { FilePermissionEnum.READ.getId() }); JSONObject result = new JSONObject(); if (path != null && userOrGroupId.length > 0 && _permissions.length > 0) { // build valid permissions set Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>(); for (String permission : _permissions) { FilePermissionEnum perm = FilePermissionEnum.resolve(permission); if (perm != null) { validPermissions.add(perm); }/* ww w . j a v a 2 s . co m*/ } JSONArray permissionAddResultArray = new JSONArray(); for (String id : userOrGroupId) { JSONObject individualResult = new JSONObject(); boolean storeResult = FileStorer .storeFilePermissions(new FilePermissionMetadata(path, id, validPermissions)); if (storeResult) { individualResult.put("status", String.format("Added permission for path %s and user/role %s", path, id)); } else { individualResult.put("status", String.format("Failed to add permission for path %s and user/role %s", path, id)); } permissionAddResultArray.put(individualResult); } result.put("status", "Operation finished. Check statusArray for details."); result.put("statusArray", permissionAddResultArray); } else { result.put("status", "Path or user group parameters not found"); } writeOut(out, result.toString(2)); }
From source file:pt.webdetails.cfr.CfrContentGenerator.java
@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON) public void deletePermissions(OutputStream out) throws JSONException, IOException { String path = checkRelativePathSanity(getRequestParameters().getStringParameter(pathParameterPath, null)); String[] userOrGroupId = getRequestParameters().getStringArrayParameter(pathParameterGroupOrUserId, new String[] {}); JSONObject result = new JSONObject(); if (path != null || (userOrGroupId != null && userOrGroupId.length > 0)) { if (userOrGroupId == null || userOrGroupId.length == 0) { if (FileStorer.deletePermissions(path, null)) { result.put("status", "Permissions deleted"); } else { result.put("status", "Error deleting permissions"); }/*from ww w. j av a2s. com*/ } else { JSONArray permissionDeleteResultArray = new JSONArray(); for (String id : userOrGroupId) { JSONObject individualResult = new JSONObject(); boolean deleteResult = FileStorer.deletePermissions(path, id); if (deleteResult) { individualResult.put("status", String.format("Permission for %s and path %s deleted.", id, path)); } else { individualResult.put("status", String.format("Failed to delete permission for %s and path %s.", id, path)); } permissionDeleteResultArray.put(individualResult); } result.put("status", "Multiple permission deletion. Check Status array"); result.put("statusArray", permissionDeleteResultArray); } } else { result.put("status", "Required arguments user/role and path not found"); } writeOut(out, result.toString(2)); }
From source file:charitypledge.Pledge.java
public void JsonWrite(String[] args) { String[] values = args;//from w w w . j av a 2 s. c om JSONObject obj = new JSONObject(); JSONArray objArray = new JSONArray(); try { if (args == null || values.length == 0) { throw new Exception("Noting to write to file"); } else { String title = ""; String value = ""; for (int i = (values.length - 1); i >= 0; i--) { if ((i % 2) == 0) { title = values[i]; obj.put(title, value); } else { value = values[i]; } } objArray.put(obj); } try { try { InputStream foo = new FileInputStream(JSONFile); JSONTokener t = new JSONTokener(foo); JSONObject json = new JSONObject(t); foo.close(); FileWriter file = new FileWriter(JSONFile); json.append("contributors", obj); file.write(json.toString(5)); file.close(); tableRefresh(); } catch (FileNotFoundException e) { JSONWriter jsonWriter; try { jsonWriter = new JSONWriter(new FileWriter(JSONFile)); jsonWriter.object(); jsonWriter.key("contributors"); jsonWriter.array(); jsonWriter.endArray(); jsonWriter.endObject(); InputStream foo = new FileInputStream(JSONFile); JSONTokener t = new JSONTokener(foo); JSONObject json = new JSONObject(t); foo.close(); FileWriter file = new FileWriter(JSONFile); json.append("contributors", obj); file.write(json.toString(5)); file.close(); tableRefresh(); } catch (IOException f) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { int pic = JOptionPane.ERROR_MESSAGE; JOptionPane.showMessageDialog(null, e, "", pic); } }
From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java
public String process(IParameterProvider requestParams, IPentahoSession userSession) throws InvalidOperationException { String methodString = requestParams.getStringParameter("method", "none"); JSONObject reply = null; try {// w w w .j a v a 2 s . c o m Method mthd = Method.valueOf(methodString.toUpperCase()); switch (mthd) { case DELETE: reply = deleteRecord(requestParams); break; case GET: logger.error("get requests to PersistenceEngine are no longer supported. " + "please use the SimplePersistence API."); return "{'result': false}"; case STORE: reply = store(requestParams); break; case QUERY: PentahoSessionUtils psu = new PentahoSessionUtils(); if (!psu.getCurrentSession().isAdministrator()) { throw new SecurityException("Arbitrary querying is only available to admins"); } reply = query(requestParams); break; } if (reply == null) { logger.error("Reply to request is null"); return "{'result': false}"; } return reply.toString(JSON_INDENT); } catch (IllegalArgumentException e) { logger.error("Invalid method: " + methodString); return "{'result': false}"; } catch (JSONException e) { logger.error("error processing: " + methodString); return "{'result': false}"; } }
From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java
public ODocument createDocument(String baseClass, JSONObject json) { ODocument doc = new ODocument(baseClass); @SuppressWarnings("unchecked") Iterator<String> fields = json.keys(); while (fields.hasNext()) { String field = fields.next(); if (field.equals("key")) { continue; }//from w w w . j av a 2 s . c o m try { Object value = json.get(field); if (value instanceof JSONObject) { doc.field(field, createDocument(baseClass + "_" + field, (JSONObject) value)); JSONObject obj = json.getJSONObject(field); logger.debug("obj:" + obj.toString(JSON_INDENT)); } else { doc.field(field, value); } } catch (JSONException e) { logger.error(e); } } return doc; }