Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key, int defaultValue) 

Source Link

Document

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number.

Usage

From source file:com.mikecorrigan.trainscorekeeper.ScoreButton.java

public void setButtonSpec(JSONObject jsonButton) {
    this.jsonButton = jsonButton;

    String name = jsonButton.optString(JsonSpec.BUTTON_NAME, JsonSpec.DEFAULT_BUTTON_NAME);
    setText(name);//  www.  j av  a  2s  . co m

    int value = jsonButton.optInt(JsonSpec.BUTTON_VALUE, JsonSpec.DEFAULT_BUTTON_VALUE);
    if (value < 0) {
        setTextColor(Color.RED);
    }
}

From source file:com.appsimobile.appsii.module.weather.loader.WeatherDataParser.java

@Nullable
private static WeatherData parseWeatherData(String woeid, SimpleDateFormat simpleDateFormat,
        JSONObject weatherJsonObj) throws ResponseParserException, JSONException, ParseException {
    SimpleJson weatherJson = new SimpleJson(weatherJsonObj);
    String city = weatherJson.optString("location.city");

    if (city == null) {
        String country = weatherJson.optString("location.country");
        String region = weatherJson.optString("location.region");
        if (country != null && region != null) {
            city = TextUtils.join(", ", new String[] { country, region });
        } else if (country != null) {
            city = country;//from w w  w . j a va2s.com
        }
    }

    if (city == null) {
        Log.w("WeatherDataParser", "Error in weather-query. Ignoring location");
        return null;
    }

    WeatherData weatherData = new WeatherData();

    weatherData.location = city;

    weatherData.windChill = weatherJson.getInt("wind.chill", Integer.MIN_VALUE);
    weatherData.windDirection = weatherJson.getInt("wind.direction", Integer.MIN_VALUE);
    weatherData.windSpeed = (float) weatherJson.getDouble("wind.speed", Float.MIN_VALUE);

    weatherData.atmosphereHumidity = weatherJson.getInt("atmosphere.humidity", Integer.MIN_VALUE);
    weatherData.atmospherePressure = (float) weatherJson.getDouble("atmosphere.pressure", Float.MIN_VALUE);
    weatherData.atmosphereRising = weatherJson.getInt("atmosphere.rising", Integer.MIN_VALUE);
    weatherData.atmosphereVisible = (float) weatherJson.getDouble("atmosphere.visibility", Float.MIN_VALUE);

    weatherData.sunrise = weatherJson.optString("astronomy.sunrise");
    weatherData.sunset = weatherJson.optString("astronomy.sunset");

    weatherData.nowConditionCode = weatherJson.getInt("item.condition.code", WeatherData.INVALID_CONDITION);
    weatherData.nowConditionText = weatherJson.optString("item.condition.text");
    weatherData.nowTemperature = weatherJson.getInt("item.condition.temp", WeatherData.INVALID_TEMPERATURE);

    JSONArray forecastArray = weatherJson.optJsonArray("item.forecast");

    if (forecastArray != null) {

        int fl = forecastArray.length();
        for (int k = 0; k < fl; k++) {
            JSONObject forecastJson = forecastArray.getJSONObject(k);
            WeatherData.Forecast forecast = new WeatherData.Forecast();

            String date = forecastJson.optString("date");
            long millis = simpleDateFormat.parse(date).getTime();

            forecast.julianDay = Time.getJulianDay(millis, 0);
            forecast.conditionCode = forecastJson.optInt("code", WeatherData.INVALID_CONDITION);
            forecast.forecastText = forecastJson.optString("text");
            forecast.low = forecastJson.optInt("low", WeatherData.INVALID_TEMPERATURE);
            forecast.high = forecastJson.optInt("high", WeatherData.INVALID_TEMPERATURE);

            weatherData.forecasts.add(forecast);
        }

    }
    weatherData.woeid = woeid;
    return weatherData;
}

From source file:org.steveleach.scoresheet.support.JsonCodec.java

/**
 * Populates a model from a JSON string representation.
 *
 * @param model/*from  w ww  . ja  v  a  2s .  c  o  m*/
 *          the model to load the data into
 * @param json
 * @throws JSONException
 */
public void fromJson(ScoresheetModel model, String json) throws JSONException {
    model.getEvents().clear();

    if ((json == null) || (json.length() == 0)) {
        throw new JSONException("No content provided for JSON decoder");
    }

    JSONObject root = new JSONObject(json);

    if (root.has("homeTeam")) {
        loadTeam(root.getJSONObject("homeTeam"), model.getHomeTeam());
        loadTeam(root.getJSONObject("awayTeam"), model.getAwayTeam());
    } else {
        model.getHomeTeam().setName(root.optString("homeTeamName", "Home"));
        model.getAwayTeam().setName(root.optString("awayTeamName", "Home"));
    }
    model.setGameLocation(root.optString("location", ""));

    model.setGameDateTime(getDate(root.optString("gameDate", "")));

    JSONArray jsonEvents = root.getJSONArray("events");
    for (int n = 0; n < jsonEvents.length(); n++) {
        JSONObject jsonEvent = (JSONObject) jsonEvents.get(n);
        String eventType = jsonEvent.getString("eventType");
        GameEvent event = null;
        if (eventType.equals("Goal")) {
            GoalEvent goal = new GoalEvent();
            goal.setAssist1(jsonEvent.optInt("assist1", 0));
            goal.setAssist2(jsonEvent.optInt("assist2", 0));
            event = goal;
        } else if (eventType.equals("Penalty")) {
            PenaltyEvent penalty = new PenaltyEvent();
            penalty.setMinutes(jsonEvent.optInt("minutes", 2));
            penalty.setPlusMins(jsonEvent.optInt("plusMins", 0));
            event = penalty;
        } else if (eventType.equals("Period end")) {
            event = new PeriodEndEvent();
        }
        event.setSubType(jsonEvent.getString("subType"));
        event.setPeriod(jsonEvent.getInt("period"));
        event.setGameTime(jsonEvent.getString("gameTime"));
        event.setTeam(jsonEvent.getString("team"));
        event.setPlayer(getInt(jsonEvent.get("player")));

        model.addEvent(event);
    }
}

From source file:com.facebook.stream.StreamRenderer.java

/**
 * Renders the 'x people like this' text,
 * //from w ww. j a v a2  s.  co  m
 * @param post
 */
private void renderLikes(JSONObject post) {
    int numLikes = post.optInt("likes", 0);
    if (numLikes > 0) {
        String desc = numLikes == 1 ? "person likes this" : "people like this";
        String[] chunks = new String[] { "<div class=\"like_icon\">",
                "<img src=\"file:///android_asset/like_icon.png\"/>", "</div>", "<div class=\"num_likes\">",
                new Integer(numLikes).toString(), " ", desc, "</div>" };
        append(chunks);
    }
}

From source file:com.rapid.actions.Database.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    // This code could be optimised to only return required data, according to the outputs collection
    _logger.trace("Database action : " + jsonAction);

    // fetch the application
    Application application = rapidRequest.getApplication();

    // fetch the page
    Page page = rapidRequest.getPage();//from   w  w w  . jav a 2s.  c om

    // fetch in the sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // place holder for the object we're going to return
    JSONObject jsonData = null;

    // only if there is a query object, application, and page            
    if (_query != null && application != null && page != null) {

        // get the relevant connection
        DatabaseConnection databaseConnection = application.getDatabaseConnections()
                .get(_query.getDatabaseConnectionIndex());

        // get the connection adapter
        ConnectionAdapter ca = databaseConnection
                .getConnectionAdapter(rapidRequest.getRapidServlet().getServletContext(), application);

        // instantiate a data factory with autocommit = false;
        DataFactory df = new DataFactory(ca, false);

        // use the reusable do query function (so child database actions can use it as well)
        jsonData = doQuery(rapidRequest, jsonAction, application, df);

        // commit the data factory transaction
        df.commit();
        // close the data factory
        df.close();

    } // got query, app, and page

    // if it's null instantiate one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add it back to the data object we're returning
    jsonData.put("sequence", sequence);

    return jsonData;

}

From source file:org.apache.cordova.mediacapture.Capture.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.callbackContext = callbackContext;
    this.limit = 1;
    this.duration = 0;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
        limit = options.optLong("limit", 1);
        duration = options.optInt("duration", 0);
    }//  w  w w. j a v a2s.  c o m

    if (action.equals("getFormatData")) {
        JSONObject obj = getFormatData(args.getString(0), args.getString(1));
        callbackContext.success(obj);
        return true;
    } else if (action.equals("captureAudio")) {
        this.captureAudio();
    } else if (action.equals("captureImage")) {
        this.captureImage();
    } else if (action.equals("captureVideo")) {
        this.captureVideo(duration);
    } else {
        return false;
    }

    return true;
}

From source file:com.danlvse.weebo.model.User.java

public static User parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from ww  w  .j a v  a  2s  .co m*/

    User user = new User();
    user.id = jsonObject.optString("id", "");
    user.idstr = jsonObject.optString("idstr", "");
    user.screen_name = jsonObject.optString("screen_name", "");
    user.name = jsonObject.optString("name", "");
    user.province = jsonObject.optInt("province", -1);
    user.city = jsonObject.optInt("city", -1);
    user.location = jsonObject.optString("location", "");
    user.description = jsonObject.optString("description", "");
    user.url = jsonObject.optString("url", "");
    user.profile_image_url = jsonObject.optString("profile_image_url", "");
    user.profile_url = jsonObject.optString("profile_url", "");
    user.cover_image_phone = jsonObject.optString("cover_image_phone", "");
    user.cover_image = jsonObject.optString("cover_image", "");
    user.domain = jsonObject.optString("domain", "");
    user.weihao = jsonObject.optString("weihao", "");
    user.gender = jsonObject.optString("gender", "");
    user.followers_count = jsonObject.optInt("followers_count", 0);
    user.friends_count = jsonObject.optInt("friends_count", 0);
    user.statuses_count = jsonObject.optInt("statuses_count", 0);
    user.favourites_count = jsonObject.optInt("favourites_count", 0);
    user.created_at = jsonObject.optString("created_at", "");
    user.following = jsonObject.optBoolean("following", false);
    user.allow_all_act_msg = jsonObject.optBoolean("allow_all_act_msg", false);
    user.geo_enabled = jsonObject.optBoolean("geo_enabled", false);
    user.verified = jsonObject.optBoolean("verified", false);
    user.verified_type = jsonObject.optInt("verified_type", -1);
    user.remark = jsonObject.optString("remark", "");
    user.status = Feed.parse(jsonObject.optJSONObject("status"));
    user.allow_all_comment = jsonObject.optBoolean("allow_all_comment", true);
    user.avatar_large = jsonObject.optString("avatar_large", "");
    user.avatar_hd = jsonObject.optString("avatar_hd", "");
    user.verified_reason = jsonObject.optString("verified_reason", "");
    user.follow_me = jsonObject.optBoolean("follow_me", false);
    user.online_status = jsonObject.optInt("online_status", 0);
    user.bi_followers_count = jsonObject.optInt("bi_followers_count", 0);
    user.lang = jsonObject.optString("lang", "");

    user.star = jsonObject.optString("star", "");
    user.mbtype = jsonObject.optString("mbtype", "");
    user.mbrank = jsonObject.optString("mbrank", "");
    user.block_word = jsonObject.optString("block_word", "");

    return user;
}

From source file:com.jennifer.ui.chart.ChartBuilder.java

private void initPadding() {
    builderoptions.put("width", options.optInt("width", 400));
    builderoptions.put("height", options.optInt("height", 400));

    if (this.options.has("padding")) {

        Object padding = this.options.get("padding");

        if (padding instanceof String && "empty".equals((String) padding)) {
            JSONObject o = new JSONObject().put("left", 0).put("right", 0).put("top", 0).put("bottom", 0);
            this.builderoptions.put("padding", o);
        } else {/*w w w.j  av a 2  s  . co  m*/
            JSONObject source = (JSONObject) padding;
            JSONObject o = new JSONObject();
            o.put("left", source.optInt("left", 50));
            o.put("right", source.optInt("right", 50));
            o.put("bottom", source.optInt("bottom", 50));
            o.put("top", source.optInt("top", 50));

            this.builderoptions.put("padding", o);
        }

    } else {
        JSONObject o = new JSONObject().put("left", 50).put("right", 50).put("top", 50).put("bottom", 50);
        this.builderoptions.put("padding", o);
    }
}

From source file:com.jennifer.ui.chart.ChartBuilder.java

private void setGridAxis(JSONObject obj, JSONObject drawObject) {
    obj.remove("x");
    obj.remove("y");
    obj.remove("c");

    if (!builderoptions.has("scales")) {
        return;/*from   w  w  w.j  ava2  s .c om*/
    }

    JSONObject scales = builderoptions.getJSONObject("scales");

    if (scales.has("x") || scales.has("x1")) {
        if (drawObject.has("x1") && drawObject.getInt("x1") > -1) {
            obj.put("x", scales.getJSONArray("x1").get(drawObject.getInt("x1")));
        } else {
            obj.put("x", scales.getJSONArray("x").get(drawObject.optInt("x", 0)));
        }
    }

    if (scales.has("y") || scales.has("y1")) {
        if (drawObject.has("y1") && drawObject.getInt("y1") > -1) {
            obj.put("y", scales.getJSONArray("y1").get(drawObject.getInt("y1")));
        } else {
            obj.put("y", scales.getJSONArray("y").get(drawObject.optInt("y", 0)));
        }
    }

    if (scales.has("c")) {
        obj.put("c", scales.getJSONArray("c").get(drawObject.optInt("c", 0)));
    }

}

From source file:com.jennifer.ui.chart.ChartBuilder.java

private void drawGrid() {
    JSONObject grid = builderoptions.getJSONObject("grid");

    String[] names = JSONObject.getNames(grid);
    if (names == null)
        return;//from   w  w  w .  j a v a 2  s .  c  o m

    if (grid != null && grid.names().length() > 0) {

        // create default cusotm grid
        if (grid.has("type")) {
            grid = new JSONObject().put("c", new JSONArray().put(JSONUtil.clone(grid)));
        }

        if (!builderoptions.has("scales")) {
            builderoptions.put("scales", new JSONObject());
        }

        JSONObject scales = (JSONObject) builderoptions.getJSONObject("scales");

        JSONArray keys = grid.names();

        for (int i = 0, len = keys.length(); i < len; i++) {
            String key = keys.getString(i);
            Orient orient = Orient.CUSTOM;

            if ("x".equals(key)) {
                orient = Orient.BOTTOM;
            } else if ("y".equals(key)) {
                orient = Orient.LEFT;
            } else if ("x1".equals(key)) {
                orient = Orient.TOP;
            } else if ("y1".equals(key)) {
                orient = Orient.RIGHT;
            }

            if (!scales.has(key)) {
                scales.put(key, new JSONArray());
            }

            JSONArray scale = (JSONArray) scales.getJSONArray(key);

            Object objGrid = grid.get(key);

            if (!(objGrid instanceof JSONArray) && !(objGrid instanceof JSONArray)) {
                JSONArray o = new JSONArray();
                o.put(JSONUtil.clone(grid.getJSONObject(key)));

                grid.put(key, o);
            } else if (objGrid instanceof JSONArray) {
                grid.put(key, JSONUtil.clone((JSONArray) objGrid));
            }

            JSONArray gridObject = (JSONArray) grid.getJSONArray(key);

            for (int keyIndex = 0, gridLen = gridObject.length(); keyIndex < gridLen; keyIndex++) {

                JSONObject g = JSONUtil.clone(gridObject.getJSONObject(keyIndex));

                Class cls = grids.get(g.getString("type"));
                Grid newGrid = null;

                try {
                    newGrid = (Grid) cls
                            .getDeclaredConstructor(Orient.class, ChartBuilder.class, JSONObject.class)
                            .newInstance(orient, this, g);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                JSONObject ret = (JSONObject) newGrid.render();

                int dist = g.optInt("dist", 0);
                Transform root = (Transform) ret.get("root");

                if ("y".equals(key)) {
                    root.translate(area("x") - dist, area("y"));
                } else if ("y1".equals(key)) {
                    root.translate(area("x2") + dist, area("y"));
                } else if ("x".equals(key)) {
                    root.translate(area("x"), area("y2") + dist);
                } else if ("x1".equals(key)) {
                    root.translate(area("x"), area("y") - dist);
                }

                this.root.append(root);

                scales.getJSONArray(key).put(keyIndex, newGrid);

            }

        }
    }
}