Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static String updateModHash(Context context) {
    // Calls me.json to get the current modhash for the user
    String output = "";
    boolean errorGettingModHash = false;

    try {//from w  ww  . j  av  a  2  s  .co  m
        try {
            output = HTTPUtil.get(context, context.getString(R.string.reddit_me));
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingModHash = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingModHash && output.length() > 0) {
            JSONTokener reddit_me_tokener = new JSONTokener(output);
            JSONObject reddit_me_json = new JSONObject(reddit_me_tokener);

            JSONObject data = reddit_me_json.getJSONObject("data");

            String modhash = data.getString("modhash");

            return modhash;
        } else {
            return null;
        }
    } catch (Exception ex) {
        //         CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        //         ceh.sendEmail(ex);

        ex.printStackTrace();

        return null;
    }
}

From source file:com.dzt.uberclone.HomeFragment.java

private void postSendUberRequest(String json) {
    try {/*from  w  w  w  .ja  va 2  s  .  c  o  m*/
        JSONObject jsonObject = new JSONObject(json);
        int pendingrideid = jsonObject.getInt("pending_ride_id");
        waitForUberDriver(pendingrideid);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    showMSG("Waiting for a driver to accept");

    requestuber.setVisibility(View.INVISIBLE);
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showShortestTime(String json) {
    try {/*from  ww  w . ja va  2s  .c om*/
        JSONObject jsonObject = new JSONObject(json);
        int shortestTimeTemp = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
                .getJSONObject(0).getJSONObject("duration").getInt("value");
        shortestTime += shortestTimeTemp;
        ubercount++;
        if (ubercount == nearbyUbers) {
            displayShortestTime(shortestTime, ubercount);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.dzt.uberclone.HomeFragment.java

private void setLocationName(String json) {
    String locationname = "";
    try {/* w  w w .  j  av a 2  s.  c  o  m*/
        JSONObject jsonObject = new JSONObject(json);
        try {

            locationname = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getString("formatted_address");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("location = ", locationname);
    selectPickup.setText(locationname);
    getNearbyUbers();
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showDriverData(String json) {
    try {/*from  ww w  .j  a  v a  2 s.c o  m*/
        JSONObject jsonObject = new JSONObject(json);
        driverid = jsonObject.getString("driver_id");
        String name = jsonObject.getString("driver_name");
        String lastname = jsonObject.getString("driver_last_name");
        String vehicle = jsonObject.getString("vehicle");
        String plate = jsonObject.getString("license_plate");
        currentRideId = jsonObject.getString("rideid");

        StringBuilder sb = new StringBuilder();
        sb.append("Your driver is ");
        sb.append(name);
        sb.append(" " + lastname);
        sb.append("\n");
        sb.append(vehicle);
        sb.append(" " + plate);

        statusText.setVisibility(View.VISIBLE);
        statusText.setText(sb.toString());

        removeUbers();
        trackDriver();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

From source file:com.dzt.uberclone.HomeFragment.java

private void handleDriverTracking(String json) {
    try {/*w  ww .j a v a 2  s. com*/
        JSONObject jsonObject = new JSONObject(json);
        if (jsonObject.has("fee")) {
            trackDriverBoolean = false;
            double initialLat = jsonObject.getDouble("initial_lat");
            double initialLng = jsonObject.getDouble("initial_lng");
            double finalLat = jsonObject.getDouble("final_lat");
            double finalLng = jsonObject.getDouble("final_lng");
            String distance = jsonObject.getString("distance");
            String time = jsonObject.getString("time");
            String fee = jsonObject.getString("fee");
            String finalFee = jsonObject.getString("final_fee");

            Bundle params = new Bundle();
            params.putString("originText", initialLat + "," + initialLng);
            params.putString("destinationText", finalLat + "," + finalLng);
            params.putString("timeText", time);
            params.putString("distanceText", distance);
            params.putString("feeText", fee);
            params.putString("finalFeeText", finalFee);
            params.putString("rideId", currentRideId);
            /*
                    
            StringBuilder sb = new StringBuilder();
            sb.append("You went from ");
            sb.append(initialLat);
            sb.append(",");
            sb.append(initialLng);
            sb.append(" to ");
            sb.append(finalLat);
            sb.append(",");
            sb.append(finalLng);
            sb.append(". Your time was ");
            sb.append(time);
            sb.append(" minutes and rode a distance of ");
            sb.append(distance);
            sb.append(" KM. Your fee is $");
            sb.append(fee);
            sb.append(" and your adjusted fee is $");
            sb.append(finalFee);
                    
            Log.i("ride details", sb.toString());
            Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_LONG).show();
                    
            */

            Intent intent = new Intent(getActivity(), RideDetailsActivity.class);
            intent.putExtras(params);
            startActivity(intent);
            getActivity().finish();

        } else {
            double lat = jsonObject.getDouble("latitude");
            double lng = jsonObject.getDouble("longitude");
            addAssignedUberMarker(lat, lng);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:edu.mit.scratch.ScratchProject.java

public ScratchProject update() throws ScratchProjectException {
    try {/*from w w w.  ja  v  a2  s.  c  o m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                        + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/api/v1/project/" + this.getProjectID() + "/?format=json")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
            System.out.println(resp.getStatusLine().toString());
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("projdata:" + result.toString());
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            if (o instanceof JSONObject)
                this.creator = "" + ((JSONObject) o).get("username");
            else {
                final String val = "" + o;

                switch (key) {
                case "creator":
                    this.creator = val;
                    break;
                case "datetime_shared":
                    this.share_date = val;
                    break;
                case "description":
                    this.description = val;
                    break;
                case "favorite_count":
                    this.favorite_count = val;
                    break;
                case "id":
                    this.ID = Integer.parseInt(val);
                    break;
                case "love_count":
                    this.love_count = val;
                    break;
                case "resource_uri":
                    this.resource_uri = val;
                    break;
                case "thumbnail":
                    this.thumbnail = val;
                    break;
                case "title":
                    this.title = val;
                    break;
                case "view_count":
                    this.view_count = val;
                    break;
                default:
                    System.out.println("Missing reference:" + key);
                    break;
                }
            }
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return this;
}

From source file:com.amazon.android.contentbrowser.helper.AuthHelper.java

/**
 * Retrieves the list of possible MVPD providers from the URL found at R.string.mvpd_url in
 * custom.xml and gives them to ContentBrowser.
 *//*from   ww w. ja  va2  s . co  m*/
public void setupMvpdList() {

    try {

        String mvpdUrl = mAppContext.getResources().getString(R.string.mvpd_url);

        // The user has no MVPD URL set up.
        if (mvpdUrl.equals(DEFAULT_MVPD_URL)) {
            Log.d(TAG, "MVPD feature not used.");
            return;
        }
        String jsonStr = NetworkUtils.getDataLocatedAtUrl(mvpdUrl);

        JSONObject json = new JSONObject(jsonStr);
        JSONArray mvpdWhiteList = json.getJSONArray(MVPD_WHITE_LIST);

        for (int i = 0; i < mvpdWhiteList.length(); i++) {

            JSONObject mvpdItem = mvpdWhiteList.getJSONObject(i);
            mContentBrowser.addPoweredByLogoUrlByName(mvpdItem.getString(PreferencesConstants.MVPD_LOGO_URL),
                    mvpdItem.getString(LOGGED_IN_IMAGE));
        }

    } catch (Exception e) {
        Log.e(TAG, "Get MVPD logo urls failed!!!", e);

    }
}

From source file:game.Clue.JSONTokener.java

/**
 * Get the next value. The value can be a Boolean, Double, Integer,
 * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
 * @throws JSONException If syntax error.
 *
 * @return An object./*from w  w  w .java 2 s . co  m*/
 */
public Object nextValue() throws JSONException {
    char c = this.nextClean();
    String string;

    switch (c) {
    case '"':
    case '\'':
        return this.nextString(c);
    case '{':
        this.back();
        return new JSONObject(this);
    case '[':
        this.back();
        return new JSONArray(this);
    }

    /*
     * Handle unquoted text. This could be the values true, false, or
     * null, or it can be a number. An implementation (such as this one)
     * is allowed to also accept non-standard forms.
     *
     * Accumulate characters until we reach the end of the text or a
     * formatting character.
     */

    StringBuilder sb = new StringBuilder();
    while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
        sb.append(c);
        c = this.next();
    }
    this.back();

    string = sb.toString().trim();
    if ("".equals(string)) {
        throw this.syntaxError("Missing value");
    }
    return JSONObject.stringToValue(string);
}

From source file:org.loklak.api.iot.NMEAServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // Sample usage for each line of NMEA Sentence data
    // GPSPosition a = new GPSPosition();
    // a = parse("$GPGGA,220550,4124.7580,N,08152.2565,W,2,04,4.4,235.1,M,-34.0,M,,*7B");

    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//from ww  w.j  ava  2s.c  o  m
    }

    // Send the stream URL as stream parameter.
    String stream = post.get("stream", "");
    String minified = post.get("minified", "");

    // Download the file/Stream of NMEA data as a buffered stream.
    URL url = new URL(stream);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String NMEALine;

    JSONObject json = new JSONObject(true);
    int lines = 0;

    // Read each buffered stream line by line and parse and convert NMEA to an actual object.
    while ((NMEALine = in.readLine()) != null) {
        lines++;
        GPSPosition gpsObject = new GPSPosition();
        gpsObject = parse(NMEALine);
        json.put(String.valueOf(lines), gpsObject.toJSONString());
    }

    in.close();

    // Start the printwriter and get ready to respond with json
    PrintWriter sos = response.getWriter();
    if (minified != "true") {
        sos.print(json.toString(2));
    } else {
        sos.print(json.toString());
    }
    sos.println();

    post.finalize();
}