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.brickred.socialauth.provider.SalesForceImpl.java

/**
 * @return/*from   w w w  . j av a 2  s.c om*/
 * @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

private void parseRates(ArrayList<ContentProviderOperation> operations, JSONObject jsonObj)
        throws JSONException {

    final long updated = jsonObj.getLong(Keys.TIMESTAMP);
    final String base = jsonObj.getString(Keys.BASE);
    final JSONObject rates = jsonObj.getJSONObject(Keys.RATES);
    final Iterator iter = rates.keys();

    while (iter.hasNext()) {

        final String currency = (String) iter.next();
        final double rate = rates.getDouble(currency);

        operations.add(ConversionRate.newUpdateOperation(currency, OpenExchangeRatesSpiFactory.PROVIDER_NAME,
                updated, rate));//  www.ja v a 2 s  .  c o m
    }

}

From source file:com.t2.compassionMeditation.DeviceManagerActivity.java

/**
 * Receives a json string containing data about all of the paired sensors
 * the adds a new BioSensor for each one to the mBioSensors collection
 * /*from  w w  w . j a v a2s  . c  om*/
 * @param jsonString String containing info on all paired devices
 */
private void populateBioSensors(String jsonString) {

    Log.d(TAG, this.getClass().getSimpleName() + " populateBioSensors");

    // Now clear it out and Re-populate it.
    mBioSensors.clear();
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Boolean enabled = jsonObject.getBoolean("enabled");
            String name = jsonObject.getString("name");
            String address = jsonObject.getString("address");
            int connectionStatus = jsonObject.getInt("connectionStatus");

            if (name.equalsIgnoreCase("system")) {
                mBluetoothEnabled = enabled;
            } else {
                Log.i(TAG, "Adding sensor " + name + ", " + address + (enabled ? ", enabled" : ", disabled")
                        + " : " + Util.connectionStatusToString(connectionStatus));
                Log.i(TAG, this.getClass().getSimpleName() + " Adding sensor " + name + ", " + address
                        + (enabled ? ", enabled" : ", disabled"));
                BioSensor bioSensor = new BioSensor(name, address, enabled);

                bioSensor.mConnectionStatus = connectionStatus;
                mBioSensors.add(bioSensor);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
}

From source file:ca.viaware.dlna.webinterface.InterfaceServer.java

public InterfaceServer() throws IOException {
    JSONObject config = SettingsManager.getServerConfig().getJSONObject("webInterface");
    this.server = HttpServer.create(new InetSocketAddress(config.getString("host"), config.getInt("port")), 8);
}

From source file:cn.kangeqiu.kq.activity.GroupDetailsActivity.java

private void initDate() {
    adapter.clear();//ww w .  j av  a2s  .c  o m
    memberIds = "";
    doPullDate(false, "2050", new MCHttpCallBack() {

        @Override
        public void onSuccess(MCHttpResp resp) {
            super.onSuccess(resp);
            try {
                String resultCode = resp.getJson().getString("result_code");
                if (resultCode.equals("0")) {
                    JSONObject room = resp.getJson().getJSONObject("room");
                    hourse_name.setText(room.getString("name"));
                    invite_number.setText(room.getString("invitation_code"));
                    member_sum.setText("? (" + room.getString("member_count") + "/"
                            + room.getString("max_member_count") + ")");
                    JSONObject match = resp.getJson().getJSONObject("match");

                    match_name.setText(match.getJSONObject("team1").getString("name") + "VS"
                            + match.getJSONObject("team2").getString("name"));

                    JSONArray records = resp.getJson().getJSONArray("records");
                    // 
                    shareUtil.setShareContent(
                            "?" + room.getString("name") + ""
                                    + "???????",
                            records.getJSONObject(0).getString("icon"));
                    List<MemberInfoModel> memberArray = new ArrayList<MemberInfoModel>();

                    for (int i = 0; i < records.length(); i++) {
                        MemberInfoModel member = new MemberInfoModel();
                        member.setIcon(records.getJSONObject(i).getString("icon"));
                        member.setName(records.getJSONObject(i).getString("nickname"));
                        member.setId(records.getJSONObject(i).getString("id"));

                        memberIds += "," + records.getJSONObject(i).getString("id");
                        memberArray.add(member);
                    }
                    adapter.setMembers(memberArray);
                } else {
                    Toast.makeText(GroupDetailsActivity.this, resp.getJson().getString("message"),
                            Toast.LENGTH_SHORT).show();
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onError(MCHttpResp resp) {
            super.onError(resp);
            Toast.makeText(GroupDetailsActivity.this, resp.getErrorMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

From source file:cn.kangeqiu.kq.activity.GroupDetailsActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    shareUtil.ssoResult(requestCode, resultCode, data);
    String st1 = getResources().getString(R.string.being_added);
    String st2 = getResources().getString(R.string.is_quit_the_group_chat);
    String st3 = getResources().getString(R.string.chatting_is_dissolution);
    String st4 = getResources().getString(R.string.are_empty_group_of_news);
    String st5 = getResources().getString(R.string.is_modify_the_group_name);
    final String st6 = getResources().getString(R.string.Modify_the_group_name_successful);
    final String st7 = getResources().getString(R.string.change_the_group_name_failed_please);
    String st8 = getResources().getString(R.string.Are_moving_to_blacklist);
    final String st9 = getResources().getString(R.string.failed_to_move_into);

    final String stsuccess = getResources().getString(R.string.Move_into_blacklist_success);
    if (resultCode == RESULT_OK) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(GroupDetailsActivity.this);
            progressDialog.setMessage(st1);
            progressDialog.setCanceledOnTouchOutside(false);
        }//w  w  w  .j  a v a2  s. c o  m
        switch (requestCode) {
        case REQUEST_CODE_ADD_USER:// ?
            // final String[] newmembers = data
            // .getStringArrayExtra("newmembers");
            newIds = data.getStringExtra("id");
            progressDialog.setMessage(st1);
            progressDialog.show();
            addMembersToGroup();
            break;
        case REQUEST_CODE_EXIT: // 
            progressDialog.setMessage(st2);
            progressDialog.show();
            exitGrop();
            break;
        case REQUEST_CODE_EXIT_DELETE: // 
            progressDialog.setMessage(st3);
            progressDialog.show();
            deleteGrop();
            break;
        case REQUEST_CODE_CLEAR_ALL_HISTORY:
            // ??
            progressDialog.setMessage(st4);
            progressDialog.show();
            clearGroupHistory();
            break;

        case REQUEST_CODE_EDIT_GROUPNAME: // ??
            final String returnData = data.getStringExtra("data");
            hourse_name.setText(returnData);
            Toast.makeText(getApplicationContext(), st6, 0).show();
            // ((TextView) findViewById(R.id.group_name)).setText(returnData
            // + "("
            // + group.getAffiliationsCount()
            // + st);

            // if (!TextUtils.isEmpty(returnData)) {
            // progressDialog.setMessage(st5);
            // progressDialog.show();
            //
            // new Thread(new Runnable() {
            // public void run() {
            // try {
            // EMGroupManager.getInstance().changeGroupName(
            // groupId, returnData);
            // runOnUiThread(new Runnable() {
            // public void run() {
            // ((TextView) findViewById(R.id.group_name)).setText(returnData
            // + "("
            // + group.getAffiliationsCount()
            // + st);
            // progressDialog.dismiss();
            // Toast.makeText(getApplicationContext(),
            // st6, 0).show();
            // }
            // });
            //
            // } catch (EaseMobException e) {
            // e.printStackTrace();
            // runOnUiThread(new Runnable() {
            // public void run() {
            // progressDialog.dismiss();
            // Toast.makeText(getApplicationContext(),
            // st7, 0).show();
            // }
            // });
            // }
            // }
            // }).start();
            // }
            break;
        case REQUEST_CODE_ADD_TO_BALCKLIST:
            progressDialog.setMessage(st8);
            progressDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        EMGroupManager.getInstance().blockUser(groupId, longClickUsername);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                refreshMembers();
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), stsuccess, 0).show();
                            }
                        });
                    } catch (EaseMobException e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), st9, 0).show();
                            }
                        });
                    }
                }
            }).start();

            break;
        default:
            break;
        }
    } else if (resultCode == 30) {
        try {
            final JSONObject jsonMatch = new JSONObject(data.getStringExtra("match"));
            matchId = jsonMatch.getString("id");
            CPorgressDialog.showProgressDialog(GroupDetailsActivity.this);
            doPullDate(false, "2053", new MCHttpCallBack() {
                @Override
                public void onSuccess(MCHttpResp resp) {
                    super.onSuccess(resp);
                    CPorgressDialog.hideProgressDialog();
                    try {
                        String resultCode = resp.getJson().getString("result_code");
                        if (resultCode.equals("0")) {
                            match_name.setText(jsonMatch.getJSONObject("team1").getString("name") + "VS"
                                    + jsonMatch.getJSONObject("team2").getString("name"));
                        } else {
                            Toast.makeText(GroupDetailsActivity.this, resp.getJson().getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(MCHttpResp resp) {
                    super.onError(resp);
                    CPorgressDialog.hideProgressDialog();
                }
            });
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

From source file:com.facebook.stetho.inspector.protocol.module.Network.java

@ChromeDevtoolsMethod
public JsonRpcResult getResponseBody(JsonRpcPeer peer, JSONObject params) throws JsonRpcException {
    try {// w  ww .  j ava  2s. c o m
        String requestId = params.getString("requestId");
        return readResponseBody(requestId);
    } catch (IOException e) {
        throw new JsonRpcException(
                new JsonRpcError(JsonRpcError.ErrorCode.INTERNAL_ERROR, e.toString(), null /* data */));
    } catch (JSONException e) {
        throw new JsonRpcException(
                new JsonRpcError(JsonRpcError.ErrorCode.INTERNAL_ERROR, e.toString(), null /* data */));
    }
}

From source file:edu.msu.walajahi.sunshine.app.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from   ww  w .j  a  v  a  2s  .c o m*/
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.hunch.api.HunchCategory.java

static HunchCategory buildFromJSON(JSONObject json) {
    HunchCategory.Builder builder = getBuilder();

    // build the HunchCategory object
    try {//from w  w  w  .j  av  a2s .  com
        builder.init(json).setName(json.getString("name")).setImageUrl(json.getString("imageUrl"))
                .setUrlName(json.getString("urlName"));
    } catch (JSONException e) {
        throw new RuntimeException("could not build HunchCategory!", e);
    }

    return builder.build();
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Takes json string and parses it to map of dictionary references.
 * //from w w  w  .j a va2s.  c o  m
 * @param jsonString - JSON string to be parsed
 */
public void parseDicRef(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
        return;
    }
    Map<String, String> dicRefTemp = new HashMap<>();
    JSONObject dicRefJson;
    try {
        dicRefJson = new JSONObject(jsonString);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "getting parseJapaneseKeb()  initial expression failed: " + e.toString());
        return;
    }

    Iterator<?> keys = dicRefJson.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        String value;
        try {
            value = dicRefJson.getString(key);
            if (key != null && value != null) {
                dicRefTemp.put(key, value);
            }
        } catch (JSONException e) {
            Log.w(LOG_TAG, "parsing dicRef failed");
        }
    }
    if (dicRefTemp.size() > 0) {
        for (String key : dicRefTemp.keySet()) {
            addDicRef(key, dicRefTemp.get(key));
        }
    }

}