Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:JSON.JasonJSON.java

public static void main(String[] args) throws Exception {

    URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json");
    //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground 
    //writes a perfectly formatted JSON file that is easy to read with Java.
    // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201");

    try {//from   www.ja  v a 2  s  .c  o m

        HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection();

        //          This part will read the data returned thru HTTP and load it into memory
        //          I have this code left over from my CIT260 project.
        InputStream stream = urlCon.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        // The next lines read certain parts of the JSON data and print it out on the screen
        //Creates the JSONObject object and loads the JSON file from the URLConnection
        //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something

        JSONObject json = new JSONObject(result.toString());

        JSONObject coloradoInfo = (JSONObject) json.get("current_observation");

        StringWriter out = new StringWriter();
        json.write(out);
        String jsonTxt = json.toString();
        System.out.print(jsonTxt);

        List<String> list = new ArrayList<>();
        JSONArray array = json.getJSONArray(jsonTxt);
        System.out.print(jsonTxt);

        // for (int i =0;i<array.length();i++){
        //list.add(array.getJSONObject(i).getString("current_observation"));
        //}

        String wunderGround = "Data downloaded from: " +

                coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: "
                + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: "
                + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: "
                + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: "
                + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: "
                + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string")
                + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: "
                + coloradoInfo.get("pressure_in");

        System.out.println("\nColorado Springs Weather:");
        System.out.println("____________________________________");
        System.out.println(wunderGround);

    } catch (IOException e) {
        System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString()
                + "\nERROR: " + e.toString());
    }

}

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

public String get(final String key) throws ScratchProjectException {
    try {//w  w  w  .  j a  va 2 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(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .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);
        } 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);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";

            if (k.equals(key))
                return o.get("value") + "";
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return null;
}

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

public List<String> getVariables() throws ScratchProjectException {
    final List<String> list = new ArrayList<>();

    try {/*  w  ww.j a v a 2s .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(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .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);
        } 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);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";
            list.add(k);
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return list;
}

From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

@Override
protected List<Place> doInBackground(Void... voids) {
    URL urlO = null;/* w w w.j a va2  s .com*/
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Place place = Place.getByLocation(placeJson.get("description").toString(),
                            placeJson.get("latitude").toString(), placeJson.get("longitude").toString());

                    if (place == null) {
                        place = new Place(placeJson);
                    } else {
                        place.setDeviceId(placeJson.getString("deviceId"));
                        place.setAddress(placeJson.getString("address"));
                        place.setDateAndTime(placeJson.getString("dateAndTime"));
                        place.setLongitude(placeJson.getDouble("longitude"));
                        place.setLatitude(placeJson.getDouble("latitude"));
                        place.setRemoteId(placeJson.getString("_id"));
                    }

                    publishProgress("Saving place : " + place.getAddress());
                    place.save();

                    allPlaces.add(place);
                }
            } else {
                publishProgress("Your Cozy has no places stored.");
                return allPlaces;
            }
        } else {
            errorMessage = "Failed to parse API response";
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return allPlaces;
}

From source file:com.soomla.store.domain.data.VirtualGood.java

/**
 * Converts the current {@link VirtualGood} to a JSONObject.
 * @return a JSONObject representation of the current {@link VirtualGood}.
 *//*from w  w  w.j av a  2  s  .  c om*/
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        JSONObject priceModelObject = AbstractPriceModel.priceModelToJSONObject(mPriceModel);
        jsonObject.put(JSONConsts.GOOD_PRICE_MODEL, priceModelObject);
    } catch (JSONException e) {
        if (StoreConfig.debug) {
            Log.d(TAG, "An error occurred while generating JSON object.");
        }
    }

    return jsonObject;
}

From source file:org.godotengine.godot.Utils.java

public static Map<String, Object> jsonToMap(String jsonData) {
    JSONObject jobject = null;

    try {/*from   w w  w.  j av  a 2 s  .c  o m*/
        jobject = new JSONObject(jsonData);
    } catch (JSONException e) {
        Utils.d("JSONObject exception: " + e.toString());
    }

    Map<String, Object> retMap = new HashMap<String, Object>();
    Iterator<String> keysItr = jobject.keys();

    while (keysItr.hasNext()) {
        try {
            String key = keysItr.next();
            Object value = jobject.get(key);

            retMap.put(key, value);
        } catch (JSONException e) {
            Utils.d("JSONObject get key error" + e.toString());
        }
    }

    return retMap;
}

From source file:com.voidsearch.data.provider.facebook.objects.LikedEntry.java

public LikedEntry(JSONObject data) throws Exception {
    super(data);//from   w  ww  .  ja va  2 s .c om
    this.name = (String) data.get("name");
    this.category = (String) data.get("category");
}

From source file:net.micode.notes.gtask.remote.GTaskClient.java

public void createTask(Task task) throws NetworkFailureException {
    commitUpdate();/*from  w  w w  .j  a va 2 s  .c  o m*/
    try {
        JSONObject jsPost = new JSONObject();
        JSONArray actionList = new JSONArray();

        // action_list
        actionList.put(task.getCreateAction(getActionId()));
        jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

        // client_version
        jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);

        // post
        JSONObject jsResponse = postRequest(jsPost);
        JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
        task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new ActionFailureException("create task: handing jsonobject failed");
    }
}

From source file:net.micode.notes.gtask.remote.GTaskClient.java

public void createTaskList(TaskList tasklist) throws NetworkFailureException {
    commitUpdate();//from   ww  w . ja v  a2 s.c  om
    try {
        JSONObject jsPost = new JSONObject();
        JSONArray actionList = new JSONArray();

        // action_list
        actionList.put(tasklist.getCreateAction(getActionId()));
        jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

        // client version
        jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);

        // post
        JSONObject jsResponse = postRequest(jsPost);
        JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
        tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        throw new ActionFailureException("create tasklist: handing jsonobject failed");
    }
}

From source file:com.facebook.config.AbstractExpandedConfJSONProvider.java

private JSONObject getExpandedJSONConfig() throws JSONException {
    Set<String> traversedFiles = new HashSet<>();
    Queue<String> toTraverse = new LinkedList<>();

    // Seed the graph traversal with the root node
    traversedFiles.add(root);/*w  w w .j ava  2  s  . c  o  m*/
    toTraverse.add(root);

    // Policy: parent configs will override children (included) configs
    JSONObject expanded = new JSONObject();
    while (!toTraverse.isEmpty()) {
        String current = toTraverse.remove();
        JSONObject json = load(current);
        JSONObject conf = json.getJSONObject(CONF_KEY);
        Iterator<String> iter = conf.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            // Current config will get to insert keys before its include files
            if (!expanded.has(key)) {
                expanded.put(key, conf.get(key));
            }
        }
        // Check if the file itself has any included files
        if (json.has(INCLUDES_KEY)) {
            JSONArray includes = json.getJSONArray(INCLUDES_KEY);
            for (int idx = 0; idx < includes.length(); idx++) {
                String include = resolve(current, includes.getString(idx));
                if (traversedFiles.contains(include)) {
                    LOG.warn("Config file was included twice: " + include);
                } else {
                    toTraverse.add(include);
                    traversedFiles.add(include);
                }
            }
        }
    }

    return expanded;
}