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:com.saggezza.litrackerlite.track.TrackerC.java

private JSONObject mapToJSON(Map<String, Object> oMap) {
    return new JSONObject(oMap);
}

From source file:org.brickred.socialauth.provider.SalesForceImpl.java

/**
 * @return/*  w  w w. ja v a  2  s  . c o  m*/
 * @throws Exception
 */
private Profile getProfile() throws Exception {
    if (accessGrant.getAttribute("id") != null) {
        profileURL = (String) accessGrant.getAttribute("id");
    }
    LOG.debug("Profile URL : " + profileURL);
    Profile p = new Profile();
    Map<String, String> headerParam = new HashMap<String, String>();
    headerParam.put("Authorization", "OAuth " + accessGrant.getKey());
    headerParam.put("Content-Type", "application/json");
    headerParam.put("Accept", "application/json");
    Response serviceResponse;
    try {
        serviceResponse = authenticationStrategy.executeFeed(profileURL, MethodType.GET.toString(), null,
                headerParam, null);
        // HttpUtil.doHttpRequest(profileURL, "GET", null, headerParam);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to retrieve the user profile from  " + profileURL, e);
    }

    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
        LOG.debug("User Profile :" + result);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to read response from  " + profileURL, e);
    }
    try {
        JSONObject resp = new JSONObject(result);
        if (resp.has("user_id")) {
            p.setValidatedId(resp.getString("user_id"));
        }
        if (resp.has("first_name")) {
            p.setFirstName(resp.getString("first_name"));
        }
        if (resp.has("last_name")) {
            p.setLastName(resp.getString("last_name"));
        }
        p.setDisplayName(resp.getString("display_name"));

        p.setEmail(resp.getString("email"));
        String locale = resp.getString("locale");
        if (locale != null) {
            String a[] = locale.split("_");
            p.setLanguage(a[0]);
            p.setCountry(a[1]);
        }
        if (resp.has("photos")) {
            JSONObject photosResp = resp.getJSONObject("photos");

            if (p.getProfileImageURL() == null || p.getProfileImageURL().length() <= 0) {
                p.setProfileImageURL(photosResp.getString("thumbnail"));
            }
        }
        serviceResponse.close();
        p.setProviderId(getProviderId());
        userProfile = p;
        return p;
    } catch (Exception e) {
        throw new SocialAuthException("Failed to parse the user profile json : " + result, e);

    }
}

From source file:fi.kinetik.android.currencies.spi.openexchange.OpenExchangeRatesSpi.java

public void loadData(ArrayList<ContentProviderOperation> operations) throws IOException, RatesSpiException {

    final URLConnection connection = OpenExchangeRatesSpiFactory.sFeedURL.openConnection();

    InputStream in = null;/*from   w  w w. ja  v  a2 s.  c  om*/

    try {

        in = connection.getInputStream();

        // not efficient to read the entire feed into memory but since its
        // not that big...

        JSONObject json = new JSONObject(IOUtils.toString(in, OpenExchangeRatesSpiFactory.CHARSET));

        parseRates(operations, json);

    } catch (JSONException e) {
        throw new RatesSpiException("parsing json failed", e);
    } finally {
        IOUtils.close(in);
    }
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

/**
 * Get JSON object from specified url. It is contained in <code>list</code> item of output JSO
 * /*  ww w .j a  va2s. c  o m*/
 * @param context used to get services over
 * @param url to load data from
 * @return JSON object
 * @throws NoRouteToHostException if internet connection is not available
 * @throws AuthenticationException if authentication fails
 * @throws IOException if there is problem during data readig from server
 * @throws JSONException if returned JSON is invalid
 * @throws URISyntaxException if url is invalid
 */
public static Response<JSONObject> getJSONObjectFromUrl(Context context, GHCredentials apiCredentials,
        String url, Map<String, String> headers)
        throws NoRouteToHostException, AuthenticationException, IOException, JSONException, URISyntaxException {
    Response<String> wr = readInternetDataGet(context, apiCredentials, url, headers);
    Response<JSONObject> ret = new Response<JSONObject>();
    wr.fill(ret);
    if (!wr.notModified) {
        ret.data = new JSONObject(wr.data);
    }
    return ret;
}

From source file:com.chess.genesis.net.SocketClient.java

public synchronized JSONObject read() throws IOException, JSONException {
    connect();//from  w  w w.j  ava2 s.  c  o m

    try {
        return (JSONObject) new JSONTokener(input.readLine()).nextValue();
    } catch (final NullPointerException e) {
        return new JSONObject("{\"result\":\"error\",\"reason\":\"connection lost\"}");
    }
}

From source file:org.apache.cordova.filetransfer.FileProgressResult.java

public JSONObject toJSONObject() throws JSONException {
    return new JSONObject("{loaded:" + loaded + ",total:" + total + ",lengthComputable:"
            + (lengthComputable ? "true" : "false") + "}");
}

From source file:com.google.enterprise.connector.ldap.LdapPerson.java

public LdapPerson(String jsonString) {
    // This is implemented by saving the supplied jsonString then making a JSONObject
    // (rather than by making a JSONObject then calling the other constructor) because
    // I want to make sure that the jsonObject stored in this object is exactly the
    // the same as the one supplied. TODO(Max): think about this - is it necessary?
    this.jsonString = jsonString;
    JSONObject jo;/*ww w  .ja  va  2s  . c o  m*/
    try {
        jo = new JSONObject(jsonString);
    } catch (JSONException e) {
        throw new IllegalArgumentException();
    }
    document = new JsonDocument(jo);
    try {
        documentId = Value.getSingleValueString(document, SpiConstants.PROPNAME_DOCID);
    } catch (RepositoryException e) {
        throw new IllegalArgumentException();
    }
}

From source file:com.nascent.android.glass.glasshackto.greenpfinder.model.GreenPSpots.java

/**
 * Populates the internal places list from places found in a JSON string. This string should
 * contain a root object with a "landmarks" property that is an array of objects that represent
 * places. A place has three properties: name, latitude, and longitude.
 *//*from  w  w w  .j a  va  2s  .co m*/
private void populatePlaceList(String jsonString) {
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray array = json.optJSONArray("carparks");

        if (array != null) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.optJSONObject(i);
                ParkingLot parkingLot = jsonObjectToParkingLot(object);
                if (parkingLot != null) {
                    mParkingLots.add(parkingLot);
                }
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Could not parse landmarks JSON string", e);
    }
}

From source file:com.github.secondsun.catfactsdemo.networking.CatFactFetcherService.java

protected void onHandleIntent(Intent intent) {

    if (intent.getBooleanExtra(LOAD, false)) {

        CharSequence contentText;

        if (data.size() > 0) {
            contentText = "Data Loaded";
        } else {//from  w  w  w  .j av a 2 s  .co m
            contentText = "Awaiting Data Load";
        }
        Intent notificationIntent = new Intent(this, CatFacts.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("CatFact Fetcher").setContentText(contentText).setContentIntent(pendingIntent)
                .build();
        startForeground(ONGOING_NOTIFICATION_ID, notification);
    } else if (intent.getBooleanExtra(UNLOAD, false)) {
        stopForeground(true);
    } else {
        if (intent.getBooleanExtra(RESET, false)) {
            data.clear();
            Intent notificationIntent = new Intent(this, CatFacts.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("CatFact Fetcher").setContentText("Awaiting Data Load")
                    .setContentIntent(pendingIntent).build();
            startForeground(ONGOING_NOTIFICATION_ID, notification);
        }
        if (data.size() == 0) {
            try {
                Thread.sleep(Constants.DELAY);

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder().url(Constants.CAT_FACTS_URL).build();

                Response response = client.newCall(request).execute();

                JSONObject responseJson = new JSONObject(response.body().string());
                JSONArray facts = responseJson.getJSONArray("facts");

                ArrayList<String> toReturn = new ArrayList<>(facts.length());

                for (int i = 0; i < facts.length(); i++) {
                    toReturn.add(facts.getString(i));
                }

                data = toReturn;

            } catch (InterruptedException | IOException | JSONException e) {
                ArrayList<String> toReturn = new ArrayList<>();
                toReturn.add("Error:" + e.getMessage());
                data = toReturn;

            }
        }

        Intent notificationIntent = new Intent(this, CatFacts.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("CatFact Fetcher").setContentText("Data Available")
                .setContentIntent(pendingIntent).build();
        startForeground(ONGOING_NOTIFICATION_ID, notification);

        sendData();
    }

}

From source file:uk.bcu.services.ItunesSearchService.java

/** This is making api calls */
public void run() {
    //String api_key = "096174e14f0efd0be330fce5f1f84de2";

    String url = //"https://itunes.apple.com/search?term="+query1+"&entity=album";
            "http://itunes.apple.com/search?term=" + query1 + "&media=movie";
    //"http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" +
    //   api_key+ "&q="+query;

    boolean error = false;
    HttpClient httpclient = null;//  w  ww  .  ja  v a2s.  c  o  m
    try {
        httpclient = new DefaultHttpClient();
        HttpResponse data = httpclient.execute(new HttpGet(url));
        HttpEntity entity = data.getEntity();
        String result = EntityUtils.toString(entity, "UTF8");

        JSONObject json = new JSONObject(result);
        if (json.getInt("resultCount") > 0) {
            resultss = json.getJSONArray("results");
        } else {
            error = true;
        }
    } catch (Exception e) {
        resultss = null;
        error = true;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    super.serviceComplete(error);
}