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:pe.chalk.takoyaki.Staff.java

public void login(JSONObject accountProperties) {
    this.logger.info("?? ?: " + accountProperties.getString("username"));

    try {/*from   w  ww.j  a va2  s . c  om*/
        final HtmlPage loginPage = this.getPage("https://nid.naver.com/nidlogin.login?url=");
        final HtmlForm loginForm = loginPage.getFormByName("frmNIDLogin");

        final HtmlTextInput idInput = loginForm.getInputByName("id");
        final HtmlPasswordInput pwInput = loginForm.getInputByName("pw");
        final HtmlSubmitInput loginButton = (HtmlSubmitInput) loginForm.getByXPath("//fieldset/span/input")
                .get(0);

        final String id = accountProperties.getString("username");
        final String pw = accountProperties.getString("password");

        if (id.equals("") || pw.equals("")) {
            this.logger.notice("? ? :   ?  ");
            return;
        }

        idInput.setValueAttribute(id);
        pwInput.setValueAttribute(pw);

        Elements errors = Jsoup
                .parse(((HtmlPage) loginButton.click()).asXml()
                        .replaceFirst("<\\?xml version=\"1.0\" encoding=\"(.+)\"\\?>", "<!DOCTYPE html>"))
                .select("div.error");
        if (!errors.isEmpty())
            this.logger.warning("? ? : " + errors.text());
    } catch (Exception e) {
        this.logger.warning("? ? : " + e.getClass().getName() + ": " + e.getMessage());
    }

    this.close();
}

From source file:com.abc.driver.PersonalActivity.java

public void parseJson(JSONObject jsonResult) {
    JSONObject profileJson = null;
    try {//from w  ww  . j a va  2 s .c o  m
        try {
            profileJson = jsonResult.getJSONObject(CellSiteConstants.PROFILE);
        } catch (Exception e) {
            profileJson = null;
        }
        JSONObject userJson = jsonResult.getJSONObject(CellSiteConstants.USER);
        if (profileJson != null) {
            if (profileJson.get(CellSiteConstants.PROFILE_IMAGE_URL) != JSONObject.NULL) {
                Log.d(TAG, "get the image url");
                app.getUser().setProfileImageUrl(profileJson.getString(CellSiteConstants.PROFILE_IMAGE_URL));

            }
            if (profileJson.get(CellSiteConstants.DRIVER_LICENSE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setDriverLicenseImageUrl(profileJson.getString(CellSiteConstants.DRIVER_LICENSE_URL));
            }
            if (profileJson.get(CellSiteConstants.IDENTITY_CARD_IMAGE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setIdentityImageUrl(profileJson.getString(CellSiteConstants.IDENTITY_CARD_IMAGE_URL));
            }

            if (profileJson.get(CellSiteConstants.NAME) != JSONObject.NULL) {
                app.getUser().setName(profileJson.getString(CellSiteConstants.NAME));
            }

        }
        if (userJson.get(CellSiteConstants.MOBILE) != JSONObject.NULL) {
            app.getUser().setMobileNum(userJson.getString(CellSiteConstants.MOBILE));
        }

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

}

From source file:com.seunghyo.sunshine.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./*  w w w . j a  v  a2  s .  co  m*/
 */
private String[] 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);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

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

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java

public AcceptPacket(JSONObject json) throws JSONException {
    super(json);//ww w.j a  va  2  s  .co m
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.ACCEPT);
    this.packetType = PaxosPacketType.ACCEPT;
    this.sender = json.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    // TODO: why do we need to set paxosID here?
    this.paxosID = json.getString(PaxosPacket.Keys.ID.toString());
}

From source file:com.xfinity.ceylon_steel.controller.CustomerController.java

public static void downloadCustomers(final Context context) {
    new AsyncTask<User, Void, JSONArray>() {

        @Override//from w  w w  . ja  v a2s . c o m
        protected void onPreExecute() {
            if (UserController.progressDialog == null) {
                UserController.progressDialog = new ProgressDialog(context);
                UserController.progressDialog.setMessage("Downloading Data");
                UserController.progressDialog.setCanceledOnTouchOutside(false);
            }
            if (!UserController.progressDialog.isShowing()) {
                UserController.progressDialog.show();
            }
        }

        @Override
        protected JSONArray doInBackground(User... users) {
            try {
                User user = users[0];
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("userId", user.getUserId());
                return getJsonArray(getCustomersOfUser, parameters, context);
            } catch (IOException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) {
            if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null
                    && UserController.progressDialog.isShowing()) {
                UserController.progressDialog.dismiss();
                UserController.progressDialog = null;
            }
            if (result != null) {
                SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context);
                SQLiteDatabase database = databaseInstance.getWritableDatabase();
                SQLiteStatement compiledStatement = database
                        .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)");
                try {
                    database.beginTransaction();
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject customer = result.getJSONObject(i);
                        compiledStatement.bindAllArgsAsStrings(
                                new String[] { Integer.toString(customer.getInt("customerId")),
                                        customer.getString("customerName") });
                        long response = compiledStatement.executeInsert();
                        if (response == -1) {
                            return;
                        }
                    }
                    database.setTransactionSuccessful();
                    Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show();
                } catch (JSONException ex) {
                    Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
                    Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show();
                } finally {
                    database.endTransaction();
                    databaseInstance.close();
                }
            } else {
                Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show();
            }
        }

    }.execute(UserController.getAuthorizedUser(context));
}

From source file:org.sleeksnap.impl.HotkeyManager.java

/**
 * Initialize the input using JKeymaster
 * /* ww  w . j  a v  a  2s  . c om*/
 * @throws JSONException
 */
public void initializeInput() {
    final JSONObject keys = snapper.getConfiguration().getJSONObject("hotkeys");
    // A little sanity check, just in case we don't have ANY keys set
    if (keys == null) {
        return;
    }
    if (keys.has("crop")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("crop")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.crop();
            }
        });
    }
    if (keys.has("full")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("full")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.full();
            }
        });
    }
    if (keys.has("clipboard")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("clipboard")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.clipboard();
            }
        });
    }
    if (keys.has("file")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("file")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.selectFile();
            }
        });
    }
    if (keys.has("options")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("options")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                if (!snapper.openSettings()) {
                    snapper.getTrayIcon().displayMessage("Error",
                            "Could not open settings, is there another window open?",
                            TrayIcon.MessageType.ERROR);
                }
            }
        });
    }
    // We support active windows only on windows/linux, but OSX SOON!
    if ((Platform.isWindows() || Platform.isLinux()) && keys.has("active")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("active")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.active();
            }
        });
    }
    initialized = true;
}

From source file:com.umeng.message.example.MainActivity.java

public String getString(JSONObject json, String key) {
    String str = null;//w w w .j a  va  2s  .  c  o m
    if (json == null) {
        return str;
    }
    try {
        str = json.getString(key);
    } catch (Exception e) {
    }
    return str;
}

From source file:cc.redpen.server.api.RedPenResourceTest.java

public void testJSValidatorRuns() throws Exception {
    if (new File("redpen-server").exists()) {
        System.setProperty("REDPEN_HOME", "redpen-server/src/test");
    } else {//from w  w  w .  j a v  a  2s  .co m
        System.setProperty("REDPEN_HOME", "src/test");
    }
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate/json", WILDCARD,
            APPLICATION_JSON);
    request.setContent(String.format(
            "{\"document\":\"Test, this is a test.\",\"format\":\"json2\",\"documentParser\":\"PLAIN\",\"config\":{\"lang\":\"en\",\"validators\":{\"JavaScript\":{\"properties\":{\"script-path\":\"%s\"}}}}}",
            "resources/js").getBytes());
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    JSONArray errors = new JSONObject(response.getContentAsString()).getJSONArray("errors");
    assertTrue(errors.length() > 0);
    for (int i = 0; i < errors.length(); ++i) {
        JSONObject o = errors.getJSONObject(i).getJSONArray("errors").getJSONObject(0);
        assertEquals("[pass.js] called", o.getString("message"));
    }
}

From source file:com.example.igorklimov.popularmoviesdemo.sync.SyncAdapter.java

private void getData() {
    int sortByPreference = Utility.getSortByPreference(mContext);
    Uri contentUri = null;/*  www  .  j  a v  a 2s  .  c o  m*/

    if (sortByPreference != 4) {
        String sortType = null;
        switch (sortByPreference) {
        case 1:
            sortType = POPULARITY_DESC;
            contentUri = MovieByPopularity.CONTENT_URI;
            break;
        case 2:
            sortType = formatDate();
            contentUri = MovieByReleaseDate.CONTENT_URI;
            break;
        case 3:
            sortType = VOTE_AVG_DESC;
            contentUri = MovieByVotes.CONTENT_URI;
            break;
        }

        Cursor cursor = mContentResolver.query(contentUri, null, null, null, null);
        int page = Utility.getPagePreference(mContext);
        int count = cursor.getCount();
        if (count == 0)
            page = 1;
        Log.d(LOG_TAG, "onPerformSync: cursorCount " + count + " page: " + page);
        if (count < page * 20) {
            String jsonResponse = getJsonResponse(DISCOVER_MOVIES + SORT_BY + sortType + PAGE + page + API_KEY);

            if (jsonResponse != null) {
                JSONObject[] JsonMovies = getJsonMovies(jsonResponse);
                try {
                    Log.d(LOG_TAG, "INSERTING EXTRA DATA");
                    int i = 0;
                    for (JSONObject jsonMovie : JsonMovies) {
                        String poster = IMAGE_BASE + W_185 + jsonMovie.getString("poster_path");
                        String backdropPath = IMAGE_BASE + "/w500" + jsonMovie.getString("backdrop_path");
                        String title = jsonMovie.getString("title");
                        String releaseDate = jsonMovie.getString("release_date");
                        String vote = jsonMovie.getString("vote_average");
                        String plot = jsonMovie.getString("overview");
                        String genres = Utility.formatGenres(getGenres(jsonMovie));
                        String id = jsonMovie.getString("id");

                        ContentValues values = new ContentValues();
                        values.put(COLUMN_TITLE, title);
                        values.put(COLUMN_POSTER, poster);
                        values.put(COLUMN_RELEASE_DATE, releaseDate);
                        values.put(COLUMN_GENRES, genres);
                        values.put(COLUMN_MOVIE_ID, id);
                        values.put(COLUMN_BACKDROP_PATH, backdropPath);
                        values.put(COLUMN_AVERAGE_VOTE, vote);
                        values.put(COLUMN_PLOT, plot);

                        mContentValues[i++] = values;
                    }
                    int bulkInsert = mContentResolver.bulkInsert(contentUri, mContentValues);
                    Log.d(LOG_TAG, "onPerformSync: bulkInsert " + bulkInsert);
                    cursor.close();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.norman0406.slimgress.API.Item.ItemModMultihack.java

public ItemModMultihack(JSONArray json) throws JSONException {
    super(ItemBase.ItemType.ModMultihack, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject modResource = item.getJSONObject("modResource");
    JSONObject stats = modResource.getJSONObject("stats");
    mBurnoutInsulation = Integer.parseInt(stats.getString("BURNOUT_INSULATION"));
}