Java Code Examples for org.json.JSONObject

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/.

Source file: ExistingIncidentsActivity.java

  34 
vote

@Override protected void onResume(){
  try {
    showDialog(DIALOG_PROGRESS);
    JSONObject request=new JSONObject().put(JsonData.PARAM_REQUEST,JsonData.VALUE_REQUEST_GET_INCIDENTS_BY_POSITION).put(JsonData.PARAM_UDID,Utils.getUdid(this)).put(JsonData.PARAM_RADIUS,JsonData.VALUE_RADIUS_CLOSE).put(JsonData.PARAM_POSITION,new JSONObject().put(JsonData.PARAM_POSITION_LONGITUDE,Last_Location.longitude).put(JsonData.PARAM_POSITION_LATITUDE,Last_Location.latitude));
    AVService.getInstance(this).postJSON(new JSONArray().put(request),this);
  }
 catch (  JSONException e) {
    Log.e(Constants.PROJECT_TAG,"Error loading existing incidents",e);
  }
  super.onResume();
}
 

Example 2

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudViewParser.java

  33 
vote

public List<CloudView> parseFromString(String json) throws JSONException {
  JSONArray outlineArray=new JSONArray(json);
  List<CloudView> views=new ArrayList<CloudView>();
  for (int i=0; i < outlineArray.length(); i++) {
    JSONObject appObject=outlineArray.getJSONObject(i);
    String title=appObject.getString("title");
    String viewName=appObject.getString("name");
    views.add(new CloudView(title,viewName));
  }
  return views;
}
 

Example 3

From project android-flash-cards, under directory /src/org/thomasamsler/android/flashcards/model/.

Source file: CardSet.java

  33 
vote

public JSONObject getJSON(){
  JSONObject json=new JSONObject();
  try {
    json.put(EXTERNAL_ID_KEY,mExternalId);
    json.put(TITLE_KEY,mTitle);
    json.put(FRAGMENT_KEY,mFragmentId);
    json.put(CARD_COUNT_KEY,mCardCount);
  }
 catch (  JSONException e) {
    Log.e(AppConstants.LOG_TAG,"JSONException",e);
  }
  return json;
}
 

Example 4

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/types/.

Source file: FileFieldTypeHelper.java

  33 
vote

@Override protected void setNotNullValueFromMapToDatabase(final ContentValues values,final String value,final MobeelizerFieldAccessor field,final Map<String,String> options,final MobeelizerErrorsBuilder errors){
  try {
    JSONObject json=new JSONObject(value);
    values.put(field.getName() + _GUID,json.getString(JSON_GUID));
    values.put(field.getName() + _NAME,json.getString(JSON_NAME));
  }
 catch (  JSONException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
}
 

Example 5

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/builder/engine/.

Source file: ProcessEngineObjectBuilder.java

  32 
vote

@Override public JSONObject createJsonObject(Object modelObject) throws JSONException {
  JSONObject result=new JSONObject();
  Map<String,Object> model=getModelAsMap(modelObject);
  JSONUtil.putRetainNull(result,"version",model.get("version"));
  ProcessEngineInfo processEngineInfo=(ProcessEngineInfo)model.get("processEngineInfo");
  if (processEngineInfo != null) {
    JSONUtil.putRetainNull(result,"name",processEngineInfo.getName());
    JSONUtil.putRetainNull(result,"resourceUrl",processEngineInfo.getResourceUrl());
    JSONUtil.putRetainNull(result,"exception",processEngineInfo.getException());
  }
  return result;
}
 

Example 6

From project AlarmApp-Android, under directory /src/org/alarmapp/web/.

Source file: HttpWebClient.java

  32 
vote

public boolean checkAuthentication(AuthToken token) throws WebException {
  try {
    String response=HttpUtil.request(url("web_service/auth_token/check/"),null,createAuthHeader(token));
    LogEx.verbose("auth_token/check returned" + response);
    JSONObject obj=new JSONObject(response);
    return obj.getString("result").equals("ok");
  }
 catch (  JSONException e) {
    throw new WebException(JSON_ERROR,e);
  }
}
 

Example 7

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/.

Source file: FacebookFacade.java

  32 
vote

private String buildActionsString(Map<String,String> actionsMap){
  JSONObject actionsObject=new JSONObject();
  Set<Entry<String,String>> actionEntries=actionsMap.entrySet();
  for (  Entry<String,String> actionEntry : actionEntries) {
    try {
      actionsObject.put(RequestParameter.NAME,actionEntry.getKey());
      actionsObject.put(RequestParameter.LINK,actionEntry.getValue());
    }
 catch (    JSONException e) {
      Log.e(TAG,e.getMessage(),e);
    }
  }
  return actionsObject.toString();
}
 

Example 8

From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/.

Source file: BillingController.java

  32 
vote

/** 
 * Parse all purchases from the JSON data received from the Market Billing service.
 * @param data JSON data received from the Market Billing service.
 * @return list of purchases.
 * @throws JSONException if the data couldn't be properly parsed.
 */
private static List<Transaction> parsePurchases(JSONObject data) throws JSONException {
  ArrayList<Transaction> purchases=new ArrayList<Transaction>();
  JSONArray orders=data.optJSONArray(JSON_ORDERS);
  int numTransactions=0;
  if (orders != null) {
    numTransactions=orders.length();
  }
  for (int i=0; i < numTransactions; i++) {
    JSONObject jElement=orders.getJSONObject(i);
    Transaction p=Transaction.parse(jElement);
    purchases.add(p);
  }
  return purchases;
}
 

Example 9

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxLoadingActivity.java

  32 
vote

public void cookieCb(String url,JSONObject jo,AjaxStatus status){
  JSONObject result=new JSONObject();
  try {
    result.putOpt("cookies",jo.optJSONObject("cookies"));
  }
 catch (  JSONException e) {
  }
  showResult(result,status);
}
 

Example 10

From project android_7, under directory /src/org/immopoly/android/api/.

Source file: IS24ApiService.java

  32 
vote

/** 
 * Gets result page number 'page' from IS24 for the given lat,lon,r
 * @param lat
 * @param lon
 * @param r
 * @param page
 * @return
 * @throws MalformedURLException
 * @throws JSONException
 */
private JSONObject loadPage(double lat,double lon,float r,int page) throws MalformedURLException, JSONException {
  URL url=new URL(OAuthData.SERVER + OAuthData.SEARCH_PREFIX + "search/radius.json?realEstateType=apartmentrent&pagenumber="+ page+ "&geocoordinates="+ lat+ ";"+ lon+ ";"+ r);
  JSONObject obj=WebHelper.getHttpData(url,true,this);
  if (obj == null) {
    throw new JSONException("Got (JSONObject) null for search result. Lat: " + lat + "Lon: "+ lon+ " R: "+ r+ " pageNr: "+ page);
  }
  return obj;
}
 

Example 11

From project Android_Pusher, under directory /src/com/emorym/android_pusher/.

Source file: Pusher.java

  32 
vote

private void sendUnsubscribeMessage(PusherChannel channel){
  if (!isConnected())   return;
  try {
    String eventName=PUSHER_EVENT_UNSUBSCRIBE;
    JSONObject eventData=new JSONObject();
    eventData.put("channel",channel.getName());
    sendEvent(eventName,eventData,null);
    Log.d(LOG_TAG,"unsubscribed from channel " + channel.getName());
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
}
 

Example 12

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: Report.java

  32 
vote

/** 
 * Creates the report as a JSON Object.
 * @return the json object containing the report.
 */
public JSONObject getReportAsJSON(){
  JSONObject report=new JSONObject();
  try {
    addReportHeader(report);
    addApplicationData(report);
    addDeviceData(report);
    addLog(report);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
  return report;
}
 

Example 13

From project agraph-java-client, under directory /src/com/franz/agraph/http/handler/.

Source file: AGJSONHandler.java

  31 
vote

@Override public void handleResponse(HttpMethod method) throws IOException, AGHttpException {
  try {
    InputStream response=getInputStream(method);
    result=new JSONObject(streamToString(response));
  }
 catch (  JSONException e) {
    throw new AGHttpException(e);
  }
}
 

Example 14

From project andlytics, under directory /src/com/github/andlyticsproject/admob/.

Source file: AdmobRequest.java

  31 
vote

public static Map<String,String> getSiteList(String account,Context context) throws AdmobRateLimitExceededException, AdmobInvalidTokenException, AdmobAccountRemovedException, NetworkException, AdmobGenericException, AdmobAskForPasswordException, AdmobInvalidRequestException {
  Map<String,String> result=new HashMap<String,String>();
  String token=authenticateAdmobAccount(account,context);
  JSONArray data=AdmobRequest.getData(context,account,token,"site","search",new String[]{});
  for (int i=0; i < data.length(); i++) {
    JSONObject adObject;
    try {
      adObject=new JSONObject(data.get(i).toString());
      String id=adObject.getString("id");
      String name=adObject.getString("name");
      result.put(id,name);
    }
 catch (    JSONException e) {
      throw new AdmobGenericException(e);
    }
  }
  return result;
}
 

Example 15

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Skandiabanken.java

  31 
vote

@Override public Urllib login() throws LoginException, BankException {
  urlopen=new Urllib();
  HashMap<String,String> headers=urlopen.getHeaders();
  headers.put(HTTP_HEADER_SMARTREFILL_APPLICATION_ID,"se.skandiabanken.android.wallet");
  headers.put(HTTP_HEADER_SMARTREFILL_APPLICATION_VERSION,"9");
  headers.put(HTTP_HEADER_SMARTREFILL_COUNTRY_CODE,countryCode);
  headers.put(HTTP_HEADER_SMARTREFILL_CUSTOMER_OWNER,customerOwner);
  headers.put(HTTP_HEADER_SMARTREFILL_DEVICE_ID,getDeviceId());
  headers.put(HTTP_HEADER_SMARTREFILL_INFLOW,INFLOW_ANDROID);
  urlopen.setUserAgent(null);
  String loginUrl=getBaseUrlWithCustomerOwner() + "/login";
  List<NameValuePair> postData=new ArrayList<NameValuePair>();
  postData.add(new BasicNameValuePair("username",username));
  postData.add(new BasicNameValuePair("password",password));
  try {
    String loginResponse=urlopen.open(loginUrl,postData);
    JSONObject obj=new JSONObject(loginResponse);
    customerId=(int)obj.getLong("id");
    urlopen.addHeader("x-smartrefill-customer","" + customerId);
  }
 catch (  HttpResponseException e) {
    if (e.getStatusCode() == 401)     throw new BankException("Inloggning misslyckad fel anv?ndarnamn eller l?senord");
 else     throw new BankException("Http fel (" + e.getStatusCode() + ") "+ e.getMessage());
  }
catch (  ClientProtocolException e) {
    throw new BankException("ClientProtocolException " + e.getMessage());
  }
catch (  IOException e) {
    throw new BankException("IOException " + e.getMessage());
  }
catch (  JSONException e) {
    throw new BankException("Ov?ntat svarsformat " + e.getMessage());
  }
  return urlopen;
}
 

Example 16

From project android-joedayz, under directory /Proyectos/AndroidFoursquare/src/com/mycompany/fsq/.

Source file: FoursquareApp.java

  31 
vote

private void getAccessToken(final String code){
  mProgress.setMessage("Getting access token ...");
  mProgress.show();
  new Thread(){
    @Override public void run(){
      Log.i(TAG,"Getting access token");
      int what=0;
      try {
        URL url=new URL(mTokenUrl + "&code=" + code);
        Log.i(TAG,"Opening URL " + url.toString());
        HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.connect();
        JSONObject jsonObj=(JSONObject)new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
        mAccessToken=jsonObj.getString("access_token");
        Log.i(TAG,"Got access token: " + mAccessToken);
      }
 catch (      Exception ex) {
        what=1;
        ex.printStackTrace();
      }
      mHandler.sendMessage(mHandler.obtainMessage(what,1,0));
    }
  }
.start();
}
 

Example 17

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/puny/android/network/util/.

Source file: DrupalJSONServerNetworkUtilityBase.java

  31 
vote

/** 
 * Connects to the JSON server, authenticates the provided username and password.
 * @param username The user's username
 * @param password The user's password
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return boolean The boolean result indicating whether the user wassuccessfully authenticated.
 */
public static boolean authenticate(String username,String password,Handler handler,final Context context){
  mSessId=connectForSessId(handler,context);
  Log.d(TAG,"sessid = " + mSessId);
  if (mSessId == null) {
    return false;
  }
  ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(PARAM_SESSION_ID,mSessId));
  params.add(new BasicNameValuePair(PARAM_USERNAME,username));
  params.add(new BasicNameValuePair(PARAM_PASSWORD,password));
  JSONObject json=prepareAndSendHttpPost(AUTH_URI,params);
  if (json == null) {
    Log.d(TAG,"auth failed");
    return false;
  }
 else {
    Log.d(TAG,"auth successful " + json.toString());
    return true;
  }
}
 

Example 18

From project android-tether, under directory /facebook/src/com/facebook/android/.

Source file: Util.java

  31 
vote

/** 
 * Parse a server response into a JSON Object. This is a basic implementation using org.json.JSONObject representation. More sophisticated applications may wish to do their own parsing. The parsed JSON is checked for a variety of error fields and a FacebookException is thrown if an error condition is set, populated with the error message and error type or code if available.
 * @param response - string representation of the response
 * @return the response as a JSON Object
 * @throws JSONException - if the response is not valid JSON
 * @throws FacebookError - if an error condition is set
 */
public static JSONObject parseJson(String response) throws JSONException, FacebookError {
  if (response.equals("false")) {
    throw new FacebookError("request failed");
  }
  if (response.equals("true")) {
    response="{value : true}";
  }
  JSONObject json=new JSONObject(response);
  if (json.has("error")) {
    JSONObject error=json.getJSONObject("error");
    throw new FacebookError(error.getString("message"),error.getString("type"),0);
  }
  if (json.has("error_code") && json.has("error_msg")) {
    throw new FacebookError(json.getString("error_msg"),"",Integer.parseInt(json.getString("error_code")));
  }
  if (json.has("error_code")) {
    throw new FacebookError("request failed","",Integer.parseInt(json.getString("error_code")));
  }
  if (json.has("error_msg")) {
    throw new FacebookError(json.getString("error_msg"));
  }
  if (json.has("error_reason")) {
    throw new FacebookError(json.getString("error_reason"));
  }
  return json;
}
 

Example 19

From project android-xbmcremote, under directory /src/org/xbmc/android/util/.

Source file: HostFactory.java

  31 
vote

/** 
 * Parses a JSON-formatted string into a Host object.
 * @param str a JSON string
 * @return a Host object that represents str, or null if an error occurred
 */
public static Host getHostFromJson(String str){
  try {
    JSONObject json=(JSONObject)new JSONTokener(str).nextValue();
    Host host=new Host();
    host.name=json.getString("name");
    host.addr=json.getString("addr");
    host.port=json.getInt("port");
    host.user=json.getString("user");
    host.pass=json.getString("pass");
    host.esPort=json.getInt("esPort");
    host.timeout=json.getInt("timeout");
    host.wifi_only=json.getBoolean("wifi_only");
    host.access_point=json.getString("access_point");
    host.mac_addr=json.getString("mac_addr");
    host.wol_wait=json.getInt("wol_wait");
    host.wol_port=json.getInt("wol_port");
    return host;
  }
 catch (  JSONException e) {
    Log.e(TAG,"Error in parseJson",e);
    return null;
  }
}
 

Example 20

From project androidTileMapEditor_1, under directory /src/it/sineo/android/tileMapEditor/.

Source file: TileMap.java

  31 
vote

/** 
 * Returns a JSON representation of this map. No transient data is stored.
 * @return
 */
public String toJSON(){
  JSONObject o=new JSONObject();
  try {
    o.put("name",name);
    o.put("rows",rows);
    o.put("columns",columns);
    o.put("scale",scale);
    o.put("xOff",xOff);
    o.put("yOff",yOff);
    for (int idxRow=0; idxRow < rows; idxRow++) {
      for (int idxCol=0; idxCol < columns; idxCol++) {
        if (tilePaths[idxRow][idxCol] != null) {
          o.put("paths_" + idxRow + "_"+ idxCol,tilePaths[idxRow][idxCol]);
          o.put("angles_" + idxRow + "_"+ idxCol,tileAngles[idxRow][idxCol]);
        }
      }
    }
  }
 catch (  JSONException jsonex) {
    jsonex.printStackTrace();
  }
  String json=o.toString();
  return json;
}
 

Example 21

From project androidtracks, under directory /src/org/sfcta/cycletracks/.

Source file: TripUploader.java

  31 
vote

private JSONObject getCoordsJSON(long tripId) throws JSONException {
  SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  mDb.openReadOnly();
  Cursor tripCoordsCursor=mDb.fetchAllCoordsForTrip(tripId);
  Map<String,Integer> fieldMap=new HashMap<String,Integer>();
  fieldMap.put(TRIP_COORDS_TIME,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME));
  fieldMap.put(TRIP_COORDS_LAT,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT));
  fieldMap.put(TRIP_COORDS_LON,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT));
  fieldMap.put(TRIP_COORDS_ALT,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT));
  fieldMap.put(TRIP_COORDS_SPEED,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED));
  fieldMap.put(TRIP_COORDS_HACCURACY,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
  fieldMap.put(TRIP_COORDS_VACCURACY,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
  JSONObject tripCoords=new JSONObject();
  while (!tripCoordsCursor.isAfterLast()) {
    JSONObject coord=new JSONObject();
    coord.put(TRIP_COORDS_TIME,df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME))));
    coord.put(TRIP_COORDS_LAT,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6);
    coord.put(TRIP_COORDS_LON,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6);
    coord.put(TRIP_COORDS_ALT,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT)));
    coord.put(TRIP_COORDS_SPEED,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED)));
    coord.put(TRIP_COORDS_HACCURACY,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY)));
    coord.put(TRIP_COORDS_VACCURACY,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY)));
    tripCoords.put(coord.getString("rec"),coord);
    tripCoordsCursor.moveToNext();
  }
  tripCoordsCursor.close();
  mDb.close();
  return tripCoords;
}
 

Example 22

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/service/.

Source file: UpdaterService.java

  31 
vote

public boolean populate(JSONArray jsonArray){
  try {
    int myVersionCode=getPackageManager().getPackageInfo(getPackageName(),0).versionCode;
    JSONObject manifest=null;
    for (int i=0; i < jsonArray.length(); i++) {
      manifest=jsonArray.getJSONObject(i);
      if (manifest.getInt("min-apk-version") <= myVersionCode)       break;
    }
    if (manifest == null)     return false;
    version=manifest.getString("version");
    versionCode=manifest.getInt("version-code");
    String abi=Build.CPU_ABI.split("-")[0];
    JSONObject binaryInfo=manifest.getJSONObject(abi);
    binaryUrl=binaryInfo.getString("binary");
    binaryMd5=binaryInfo.getString("binary-md5sum");
  }
 catch (  JSONException e) {
    return false;
  }
catch (  NameNotFoundException e) {
    Log.e(TAG,"Divided by zero...",e);
    return false;
  }
  if (version == null || versionCode == 0 || binaryUrl == null || binaryMd5 == null) {
    return false;
  }
  return true;
}
 

Example 23

From project andstatus, under directory /src/org/andstatus/app/account/.

Source file: AccountSettings.java

  31 
vote

@Override protected JSONObject doInBackground(Void... arg0){
  JSONObject jso=null;
  int what=MSG_NONE;
  String message="";
  if (!skip) {
    what=MSG_ACCOUNT_INVALID;
    try {
      if (state.myAccount.verifyCredentials(true)) {
        what=MSG_ACCOUNT_VALID;
      }
    }
 catch (    ConnectionException e) {
      what=MSG_CONNECTION_EXCEPTION;
      message=e.toString();
    }
catch (    ConnectionAuthenticationException e) {
      what=MSG_ACCOUNT_INVALID;
    }
catch (    ConnectionCredentialsOfOtherUserException e) {
      what=MSG_CREDENTIALS_OF_OTHER_USER;
    }
catch (    ConnectionUnavailableException e) {
      what=MSG_SERVICE_UNAVAILABLE_ERROR;
    }
catch (    SocketTimeoutException e) {
      what=MSG_SOCKET_TIMEOUT_EXCEPTION;
    }
  }
  try {
    jso=new JSONObject();
    jso.put("what",what);
    jso.put("message",message);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
  return jso;
}
 

Example 24

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: JsonHttpResponseHandler.java

  29 
vote

protected void handleSuccessJsonMessage(Object jsonResponse){
  if (jsonResponse instanceof JSONObject) {
    onSuccess((JSONObject)jsonResponse);
  }
 else   if (jsonResponse instanceof JSONArray) {
    onSuccess((JSONArray)jsonResponse);
  }
 else {
    onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()),(JSONObject)null);
  }
}