Example usage for org.json JSONException JSONException

List of usage examples for org.json JSONException JSONException

Introduction

In this page you can find the example usage for org.json JSONException JSONException.

Prototype

public JSONException(Throwable t) 

Source Link

Usage

From source file:com.example.android.samplesync.client.RawContact.java

/**
 * Creates and returns an instance of the RawContact from the provided JSON data.
 *
 * @param user The JSONObject containing user data
 * @return user The new instance of Sample RawContact created from the JSON data.
 *//* w  w w.  ja  v a 2 s.co  m*/
public static RawContact valueOf(JSONObject contact) {

    try {
        final String userName = !contact.isNull("u") ? contact.getString("u") : null;
        final int serverContactId = !contact.isNull("i") ? contact.getInt("i") : -1;
        // If we didn't get either a username or serverId for the contact, then
        // we can't do anything with it locally...
        if ((userName == null) && (serverContactId <= 0)) {
            throw new JSONException("JSON contact missing required 'u' or 'i' fields");
        }

        final int rawContactId = !contact.isNull("c") ? contact.getInt("c") : -1;
        final String firstName = !contact.isNull("f") ? contact.getString("f") : null;
        final String lastName = !contact.isNull("l") ? contact.getString("l") : null;
        final String cellPhone = !contact.isNull("m") ? contact.getString("m") : null;
        final String officePhone = !contact.isNull("o") ? contact.getString("o") : null;
        final String homePhone = !contact.isNull("h") ? contact.getString("h") : null;
        final String email = !contact.isNull("e") ? contact.getString("e") : null;
        final String status = !contact.isNull("s") ? contact.getString("s") : null;
        final String avatarUrl = !contact.isNull("a") ? contact.getString("a") : null;
        final boolean deleted = !contact.isNull("d") ? contact.getBoolean("d") : false;
        final long syncState = !contact.isNull("x") ? contact.getLong("x") : 0;
        return new RawContact(userName, null, firstName, lastName, cellPhone, officePhone, homePhone, email,
                status, avatarUrl, deleted, serverContactId, rawContactId, syncState, false);
    } catch (final Exception ex) {
        Log.i(TAG, "Error parsing JSON contact object" + ex.toString());
    }
    return null;
}

From source file:org.immopoly.android.api.IS24ApiService.java

/**
 * Gets result page number 'page' from IS24 for the given lat,lon,r
 * @param lat/* w w w.  j  av a2  s . c om*/
 * @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) { // does this ever happen?
        throw new JSONException("Got (JSONObject) null for search result. Lat: " + lat + "Lon: " + lon + " R: "
                + r + " pageNr: " + page);
    }
    return obj;
}

From source file:com.check.v3.asynchttp.JsonHttpResponseHandler.java

@Override
public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) {
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        new Thread(new Runnable() {
            @Override//  w  w w  .j a  va2s. c om
            public void run() {
                try {
                    final Object jsonResponse = parseResponse(responseBytes);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            if (jsonResponse instanceof JSONObject) {
                                onSuccess(statusCode, headers, (JSONObject) jsonResponse);
                            } else if (jsonResponse instanceof JSONArray) {
                                onSuccess(statusCode, headers, (JSONArray) jsonResponse);
                            } else {
                                onFailure(statusCode, headers, new JSONException(
                                        "Unexpected response type " + jsonResponse.getClass().getName()),
                                        (JSONObject) null);
                            }

                        }
                    });
                } catch (final JSONException ex) {
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            onFailure(statusCode, headers, ex, (JSONObject) null);
                        }
                    });
                }
            }
        }).start();
    } else {
        onSuccess(statusCode, headers, new JSONObject());
    }
}

From source file:com.check.v3.asynchttp.JsonHttpResponseHandler.java

@Override
public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes,
        final Throwable throwable) {
    if (responseBytes != null) {
        new Thread(new Runnable() {
            @Override/* w ww.j a  va2  s . c o m*/
            public void run() {
                try {
                    final Object jsonResponse = parseResponse(responseBytes);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            if (jsonResponse instanceof JSONObject) {
                                onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse);
                            } else if (jsonResponse instanceof JSONArray) {
                                onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse);
                            } else if (jsonResponse instanceof String) {
                                onFailure(statusCode, headers, (String) jsonResponse, throwable);
                            } else {
                                onFailure(statusCode, headers, new JSONException(
                                        "Unexpected response type " + jsonResponse.getClass().getName()),
                                        (JSONObject) null);
                            }
                        }
                    });

                } catch (final JSONException ex) {
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            onFailure(statusCode, headers, ex, (JSONObject) null);
                        }
                    });

                }
            }
        }).start();
    } else {
        Log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)");
        onFailure(statusCode, headers, throwable, (JSONObject) null);
    }
}

From source file:com.vk.sdkweb.api.model.VKList.java

@Override
public VKApiModel parse(JSONObject response) throws JSONException {
    throw new JSONException("Operation is not supported while class is generic");
}

From source file:cn.com.lowe.android.tools.net.response.JsonHttpResponseHandler.java

private Object parseResponse(String content) throws JSONException {
    if (content.startsWith("[") && content.endsWith("]")) {
        return new JSONArray(content);
    } else if (content.startsWith("{") && content.endsWith("}")) {
        return new JSONObject(content);
    } else {//from   w ww .  ja  va 2  s  .  c  om
        throw new JSONException("response is not json");
    }
}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

@Override
public String toString() {
    JSONObject jsonObject = null;/*from   w ww  .  j a va  2s  . c  om*/
    try {
        if (type == BayeuxMessage.HANDSHAKE_REQ) {
            jsonObject = convertHandshakeReq();
        } else if (type == BayeuxMessage.HANDSHAKE_RESP) {
            jsonObject = convertHandshakeResp();
        } else if (type == BayeuxMessage.CONNECT_REQ) {
            jsonObject = convertConnectReq();
        } else if (type == BayeuxMessage.CONNECT_RESP) {
            jsonObject = convertConnectResp();
        } else if (type == BayeuxMessage.DISCONNECT_REQ) {
            jsonObject = convertDisconnectReq();
        } else if (type == BayeuxMessage.DISCONNECT_RESP) {
            jsonObject = convertDisconnectResp();
        } else if (type == BayeuxMessage.SUBSCRIBE_REQ) {
            jsonObject = convertSubscribeReq();
        } else if (type == BayeuxMessage.SUBSCRIBE_RESP) {
            jsonObject = convertSubscribeResp();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_REQ) {
            jsonObject = convertUnsubscribeReq();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_RESP) {
            jsonObject = convertUnsubscribeResp();
        } else if (type == BayeuxMessage.PUBLISH_REQ) {
            jsonObject = convertPublishReq();
        } else if (type == BayeuxMessage.PUBLISH_RESP) {
            jsonObject = convertPublishResp();
        } else if (type == BayeuxMessage.DELIVER_EVENT) {
            jsonObject = convertDeliverEvent();
        } else {
            throw new JSONException("Invalid BayeuxMessageType " + type);
        }
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json", e);
    }
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(jsonObject);
    String result = null;
    try {
        result = jsonArray.toString(4);
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json array", e);
    }
    return result;
}

From source file:com.facebook.android.Facebook.java

/**
 * This function does the heavy lifting of publishing an install.
 * @param fb//  w  ww . j av a  2 s  .c  om
 * @param applicationId
 * @param context
 * @throws Exception
 */
private static void publishInstall(final Facebook fb, final String applicationId, final Context context)
        throws JSONException, FacebookError, MalformedURLException, IOException {

    String attributionId = Facebook.getAttributionId(context.getContentResolver());
    SharedPreferences preferences = context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE);
    String pingKey = applicationId + "ping";
    long lastPing = preferences.getLong(pingKey, 0);
    if (lastPing == 0 && attributionId != null) {
        Bundle supportsAttributionParams = new Bundle();
        supportsAttributionParams.putString(APPLICATION_FIELDS, SUPPORTS_ATTRIBUTION);
        JSONObject supportResponse = Util.parseJson(fb.request(applicationId, supportsAttributionParams));
        Object doesSupportAttribution = (Boolean) supportResponse.get(SUPPORTS_ATTRIBUTION);

        if (!(doesSupportAttribution instanceof Boolean)) {
            throw new JSONException(String.format("%s contains %s instead of a Boolean", SUPPORTS_ATTRIBUTION,
                    doesSupportAttribution));
        }

        if ((Boolean) doesSupportAttribution) {
            Bundle publishParams = new Bundle();
            publishParams.putString(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT);
            publishParams.putString(ATTRIBUTION_KEY, attributionId);

            String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId);

            fb.request(publishUrl, publishParams, "POST");

            // denote success since no error threw from the post.
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong(pingKey, System.currentTimeMillis());
            editor.commit();
        }
    }
}

From source file:com.smartnsoft.droid4me.ws.WebServiceCaller.java

/**
 * Invokes the {@link #getString(InputStream, String)} method, but just turn the potential {@link IOException} into a {@link JSONException}.
 *
 * @see #getString(InputStream)//from   w w  w  . ja  va 2s .  co  m
 * @see #getJson(InputStream)
 */
public static String getJson(InputStream inputStream, String encoding) throws JSONException {
    try {
        return WebServiceCaller.getString(inputStream, encoding);
    } catch (IOException exception) {
        throw new JSONException(exception.getMessage());
    }
}

From source file:com.norman0406.slimgress.API.Common.EntityBase.java

public EntityBase(JSONArray json) throws JSONException {
    if (json.length() != 3)
        throw new JSONException("invalid array size");

    mEntityGuid = json.getString(0);//from ww w  .ja  va  2 s.c  o m
    mEntityTimestamp = json.getString(1);
}