Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

private JSONObject listConfigEntries(final String gitConfigUri)
        throws IOException, SAXException, JSONException {
    WebRequest request = getGetGitConfigRequest(gitConfigUri);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject configResponse = new JSONObject(response.getText());
    assertEquals(ConfigOption.TYPE, configResponse.getString(ProtocolConstants.KEY_TYPE));
    return configResponse;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

private void assertConfigOption(final JSONObject cfg, final String k, final String v)
        throws JSONException, CoreException, IOException {
    assertEquals(k, cfg.getString(GitConstants.KEY_CONFIG_ENTRY_KEY));
    assertEquals(v, cfg.getString(GitConstants.KEY_CONFIG_ENTRY_VALUE));
    assertConfigUri(cfg.getString(ProtocolConstants.KEY_LOCATION));
    assertCloneUri(cfg.getString(GitConstants.KEY_CLONE));
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/**
 * This method is called when the JavaScript sends a message to the native side.
 * This method should be overridden in subclasses.
 * @param message : the JSON-message sent by JavaScript.
 * @return true if the message was handled by the native, false otherwise
 * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts
 * @details this method may be called from a secondary thread.
 *//*from   w ww  .  ja  v  a  2s .  c om*/
// This method must be public !!!
@JavascriptInterface
public boolean onCobaltMessage(String message) {
    try {
        final JSONObject jsonObj = new JSONObject(message);

        // TYPE
        if (jsonObj.has(Cobalt.kJSType)) {
            String type = jsonObj.getString(Cobalt.kJSType);

            //CALLBACK
            if (type.equals(Cobalt.JSTypeCallBack)) {
                String callbackID = jsonObj.getString(Cobalt.kJSCallback);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);

                return handleCallback(callbackID, data);
            }

            // COBALT IS READY
            else if (type.equals(Cobalt.JSTypeCobaltIsReady)) {
                String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null);
                String versionNative = getResources().getString(R.string.version_name);
                if (versionWeb != null && !versionWeb.equals(versionNative))
                    Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative
                            + " but Web Cobalt version is " + versionWeb + ". You should fix this. ");
                onCobaltIsReady();
                return true;
            }

            // EVENT
            else if (type.equals(Cobalt.JSTypeEvent)) {
                String event = jsonObj.getString(Cobalt.kJSEvent);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleEvent(event, data, callback);
            }

            // INTENT
            else if (type.equals(Cobalt.JSTypeIntent)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // OPEN EXTERNAL URL
                if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String url = data.getString(Cobalt.kJSUrl);
                    openExternalUrl(url);

                    return true;
                }

                // UNHANDLED INTENT
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // LOG
            else if (type.equals(Cobalt.JSTypeLog)) {
                String text = jsonObj.getString(Cobalt.kJSValue);
                Log.d(Cobalt.TAG, "JS LOG: " + text);
                return true;
            }

            // NAVIGATION
            else if (type.equals(Cobalt.JSTypeNavigation)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // PUSH
                if (action.equals(Cobalt.JSActionNavigationPush)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    push(controller, page);
                    return true;
                }

                // POP
                else if (action.equals(Cobalt.JSActionNavigationPop)) {
                    JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                    if (data != null) {
                        String page = data.getString(Cobalt.kJSPage);
                        String controller = data.optString(Cobalt.kJSController, null);
                        pop(controller, page);
                    } else
                        pop();
                    return true;
                }

                // MODAL
                else if (action.equals(Cobalt.JSActionNavigationModal)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    String callbackId = jsonObj.optString(Cobalt.kJSCallback, null);
                    presentModal(controller, page, callbackId);
                    return true;
                }

                // DISMISS
                else if (action.equals(Cobalt.JSActionNavigationDismiss)) {
                    // TODO: not present in iOS
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    dismissModal(controller, page);
                    return true;
                }

                //REPLACE
                else if (action.equals(Cobalt.JSActionNavigationReplace)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    boolean animated = data.optBoolean(Cobalt.kJSAnimated);
                    replace(controller, page, animated);
                    return true;
                }

                // UNHANDLED NAVIGATION
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // PLUGIN
            else if (type.equals(Cobalt.JSTypePlugin)) {
                mPluginManager.onMessage(mContext, this, jsonObj);
            }

            // UI
            else if (type.equals(Cobalt.JSTypeUI)) {
                String control = jsonObj.getString(Cobalt.kJSUIControl);
                JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleUi(control, data, callback);
            }

            // WEB LAYER
            else if (type.equals(Cobalt.JSTypeWebLayer)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // SHOW
                if (action.equals(Cobalt.JSActionWebLayerShow)) {
                    final JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);

                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            showWebLayer(data);
                        }
                    });

                    return true;
                }

                // UNHANDLED WEB LAYER
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // UNHANDLED TYPE
            else {
                onUnhandledMessage(jsonObj);
            }
        }

        // UNHANDLED MESSAGE
        else {
            onUnhandledMessage(jsonObj);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException");
        exception.printStackTrace();
    } catch (NullPointerException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException");
        exception.printStackTrace();
    }

    return false;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

private boolean handleUi(String control, JSONObject data, String callback) {
    try {/*from  w w w.  j a va2 s  .c  o m*/
        // PICKER
        switch (control) {
        case Cobalt.JSControlPicker:
            String type = data.getString(Cobalt.kJSType);

            // DATE
            if (type.equals(Cobalt.JSPickerDate)) {
                JSONObject date = data.optJSONObject(Cobalt.kJSDate);

                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth)
                        && date.has(Cobalt.kJSDay)) {
                    year = date.getInt(Cobalt.kJSYear);
                    month = date.getInt(Cobalt.kJSMonth) - 1;
                    day = date.getInt(Cobalt.kJSDay);
                }

                JSONObject texts = data.optJSONObject(Cobalt.kJSTexts);
                String title = texts.optString(Cobalt.kJSTitle, null);
                //String delete = texts.optString(Cobalt.kJSDelete, null);
                String clear = texts.optString(Cobalt.kJSClear, null);
                String cancel = texts.optString(Cobalt.kJSCancel, null);
                String validate = texts.optString(Cobalt.kJSValidate, null);

                showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback);

                return true;
            }

            break;
        case Cobalt.JSControlAlert:
            showAlertDialog(data, callback);
            return true;
        case Cobalt.JSControlToast:
            String message = data.getString(Cobalt.kJSMessage);
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            return true;
        default:
            break;
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    // UNHANDLED UI
    try {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI);
        jsonObj.put(Cobalt.kJSUIControl, control);
        jsonObj.put(Cobalt.kJSData, data);
        jsonObj.put(Cobalt.kJSCallback, callback);
        onUnhandledMessage(jsonObj);
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    return false;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/***********************************************************************************************************************************
 * WEB LAYER// w w w  . j a  v a 2  s  .  com
 **********************************************************************************************************************************/
private void showWebLayer(JSONObject data) {
    try {
        String page = data.getString(Cobalt.kJSPage);
        double fadeDuration = data.optDouble(Cobalt.kJSWebLayerFadeDuration, 0.3);

        Bundle bundle = new Bundle();
        bundle.putString(Cobalt.kPage, page);

        CobaltWebLayerFragment webLayerFragment = getWebLayerFragment();

        if (webLayerFragment != null) {
            webLayerFragment.setArguments(bundle);

            FragmentTransaction fragmentTransition = ((FragmentActivity) mContext).getSupportFragmentManager()
                    .beginTransaction();

            if (fadeDuration > 0) {
                fragmentTransition.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
                        android.R.anim.fade_in, android.R.anim.fade_out);
            } else {
                fragmentTransition.setTransition(FragmentTransaction.TRANSIT_NONE);
            }

            if (CobaltActivity.class.isAssignableFrom(mContext.getClass())) {
                // Dismiss current Web layer if one is already shown
                CobaltActivity activity = (CobaltActivity) mContext;
                Fragment currentFragment = activity.getSupportFragmentManager()
                        .findFragmentById(activity.getFragmentContainerId());
                if (currentFragment != null
                        && CobaltWebLayerFragment.class.isAssignableFrom(currentFragment.getClass())) {
                    ((CobaltWebLayerFragment) currentFragment).dismissWebLayer(null);
                }

                // Shows Web layer
                if (activity.findViewById(activity.getFragmentContainerId()) != null) {
                    fragmentTransition.add(activity.getFragmentContainerId(), webLayerFragment);
                    fragmentTransition.commit();
                } else if (Cobalt.DEBUG)
                    Log.e(Cobalt.TAG, TAG + " - showWebLayer: fragment container not found");
            }
        } else if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showWebLayer: getWebLayerFragment returned null!");
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showWebLayer: JSONException");
        exception.printStackTrace();
    }
}

From source file:jessmchung.groupon.parsers.TextAdParser.java

@Override
public TextAd parse(JSONObject json) throws JSONException {
    TextAd obj = new TextAd();
    if (json.has("headline"))
        obj.setHeadline(json.getString("headline"));
    if (json.has("line1"))
        obj.setLine1(json.getString("line1"));
    if (json.has("line2"))
        obj.setLine2(json.getString("line2"));

    return obj;/*from www  .  j av  a 2  s . co m*/
}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {//from   w  w w . j a  v a2  s  .  c  o  m
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:com.hackathon.gavin.string.parser.MyAccountParser.java

public static ArrayList convertToArrayList(JSONArray orginalData) {
    ArrayList<String> allElements = new ArrayList<String>();
    for (int i = 0; i < orginalData.length(); i++) {
        try {//from ww w .  java 2  s  . co m
            JSONObject obj = orginalData.getJSONObject(i);
            allElements.add(Integer.toString(obj.getInt("id")));
            allElements.add(Integer.toString(obj.getInt("units")));
            allElements.add(obj.getString("instrument"));
            allElements.add(String.valueOf(obj.getDouble("price")));
            System.out.println(allElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return allElements;
}

From source file:org.openhab.habdroid.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, JSONObject widgetJson) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    try {//w w  w . j  a  v  a2 s  .com
        if (widgetJson.has("item")) {
            this.setItem(new OpenHABItem(widgetJson.getJSONObject("item")));
        }
        if (widgetJson.has("linkedPage")) {
            this.setLinkedPage(new OpenHABLinkedPage(widgetJson.getJSONObject("linkedPage")));
        }
        if (widgetJson.has("mappings")) {
            JSONArray mappingsJsonArray = widgetJson.getJSONArray("mappings");
            for (int i = 0; i < mappingsJsonArray.length(); i++) {
                JSONObject mappingObject = mappingsJsonArray.getJSONObject(i);
                OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingObject.getString("command"),
                        mappingObject.getString("label"));
                mappings.add(mapping);
            }
        }
        if (widgetJson.has("type"))
            this.setType(widgetJson.getString("type"));
        if (widgetJson.has("widgetId"))
            this.setId(widgetJson.getString("widgetId"));
        if (widgetJson.has("label"))
            this.setLabel(widgetJson.getString("label"));
        if (widgetJson.has("icon"))
            this.setIcon(widgetJson.getString("icon"));
        if (widgetJson.has("url"))
            this.setUrl(widgetJson.getString("url"));
        if (widgetJson.has("minValue"))
            this.setMinValue((float) widgetJson.getDouble("minValue"));
        if (widgetJson.has("maxValue"))
            this.setMaxValue((float) widgetJson.getDouble("maxValue"));
        if (widgetJson.has("step"))
            this.setStep((float) widgetJson.getDouble("step"));
        if (widgetJson.has("refresh"))
            this.setRefresh(widgetJson.getInt("refresh"));
        if (widgetJson.has("period"))
            this.setPeriod(widgetJson.getString("period"));
        if (widgetJson.has("service"))
            this.setService(widgetJson.getString("service"));
        if (widgetJson.has("height"))
            this.setHeight(widgetJson.getInt("height"));
        if (widgetJson.has("iconcolor"))
            this.setIconColor(widgetJson.getString("iconcolor"));
        if (widgetJson.has("labelcolor"))
            this.setLabelColor(widgetJson.getString("labelcolor"));
        if (widgetJson.has("valuecolor"))
            this.setValueColor(widgetJson.getString("valuecolor"));
        if (widgetJson.has("encoding"))
            this.setEncoding(widgetJson.getString("encoding"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (widgetJson.has("widgets")) {
        try {
            JSONArray childWidgetJsonArray = widgetJson.getJSONArray("widgets");
            for (int i = 0; i < childWidgetJsonArray.length(); i++) {
                new OpenHABWidget(this, childWidgetJsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.parent.addChildWidget(this);
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {//from   w ww  .j a v a  2  s.  c  om
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            String headerKey = iter.next().toString();
            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();
                headerValues.put(headers.getString(headerKey));
            }
            connection.setRequestProperty(headerKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}