Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:fr.openbike.android.io.RemoteStationsSyncHandler.java

/** {@inheritDoc} */
@Override//w  w w  . j a  v a 2s  .  c  o m
public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException {
    long version = jsonBikes.getLong(VERSION);
    String message = jsonBikes.optString(MESSAGE);
    if (version > mCurrentVersion) {
        return null;
    } else {
        JSONArray stations = jsonBikes.optJSONArray(STATIONS);
        if (stations != null) {
            if (dbAdapter.syncStations(stations)) { // Need
                // Update
                return null;
            }
        }
    }
    return message;
}

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void updateLocateHistory(JSONObject messageIn, boolean blocked, String msgType, String time)
        throws JSONException { // Read current history
    SharedPreferences sp = myContext.getSharedPreferences(LocationService.PREFS_NAME, Context.MODE_PRIVATE);
    String historyJsonStr = sp.getString(LocationService.HISTORY_NAME, "{}");
    JSONObject history = new JSONObject(historyJsonStr);
    if (CHAT.equals(msgType)) { // CHAT history, save hole message
        JSONArray chatMessages = history.optJSONArray("chatMessages");
        if (chatMessages == null)
            chatMessages = new JSONArray();
        //Log.d(TAG, "CHAT history TIME: " + time);
        messageIn.put("time", Long.parseLong(time));
        chatMessages.put(messageIn.toString());
        if (chatMessages.length() > 100)
            chatMessages.remove(0); // store only last 100 chat messages
        history.put("chatMessages", chatMessages);
    } else {// Current LOCATE
        String member = messageIn.optString("memberName", "");
        if (blocked)
            member = "\u2717 " + member;
        JSONObject updateStatus = new JSONObject();
        updateStatus.put("member", member);
        updateStatus.put("team", messageIn.optString("teamId", ""));
        updateStatus.put("date", getDateAndTimeString(System.currentTimeMillis()));
        updateStatus.put("target", messageIn.optString("target", ""));
        history.put("updateStatus", updateStatus);
        // History LOCATE lines...
        JSONArray historyLines = history.optJSONArray("lines");
        if (historyLines == null)
            historyLines = new JSONArray();
        String target;/*from  www .  java 2 s  .c o  m*/
        if (updateStatus.getString("target").equals(""))
            target = updateStatus.optString("team");
        else
            target = updateStatus.optString("target");
        String historyLine = updateStatus.getString("member") + " (" + target + ") "
                + updateStatus.getString("date") + "\n";
        historyLines.put(historyLine);
        if (historyLines.length() > 200)
            historyLines.remove(0); // store only last 200 locate queries
        history.put("lines", historyLines);
    }
    // Save new history
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(LocationService.HISTORY_NAME, history.toString());
    editor.commit();
    //Log.d(TAG, "history:" + history.toString());
}

From source file:org.ESLM.Parser.JSONProtoLessonParser.java

private void parseLesson() throws BadFormedJSONExerciseException {
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject jsonLesson = new JSONObject(tokener);
    String title = jsonLesson.optString("title", "Untitled Lesson");
    JSONArray jsonExercises = jsonLesson.optJSONArray("exercises");
    Instruction[] exercises = parseExercises(jsonExercises);
    parsedLesson = new ProtoLesson(title);
    for (Instruction instruction : exercises)
        parsedLesson.addExercise(instruction);
}

From source file:com.basetechnology.s0.agentserver.field.ChoiceField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("choice_field"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null;
    List<String> choices = new ArrayList<String>();
    if (fieldJson.has("choices")) {
        JSONArray choicesJson = fieldJson.optJSONArray("choices");
        int n = choicesJson.length();
        for (int i = 0; i < n; i++)
            choices.add(choicesJson.optString(i));
    }//from  w  ww .  j a va  2 s. co  m
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new ChoiceField(symbolTable, name, label, description, defaultValue, choices, nominalWidth, compute);
}

From source file:com.sina.weibo.sdk_lib.openapi.models.PoiList.java

public static PoiList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*w  ww  .  j a v a2s  . c  om*/

    PoiList poiList = new PoiList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        poiList.totalNumber = jsonObject.optString("total_number");
        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            poiList.pois = new ArrayList<Poi>(length);
            for (int ix = 0; ix < length; ix++) {
                poiList.pois.add(Poi.parse(jsonArray.optJSONObject(ix)));
            }
        }

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

From source file:com.phelps.liteweibo.model.weibo.Group.java

public static Group parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//w  ww  .  j  a  v  a  2s.c o  m

    Group group = new Group();
    group.user = User.parse(jsonObject.optJSONObject("user"));
    group.id = jsonObject.optString("id");
    group.idStr = jsonObject.optString("idstr");
    group.name = jsonObject.optString("name");
    group.mode = jsonObject.optString("mode");
    group.visible = jsonObject.optInt("visible");
    group.like_count = jsonObject.optInt("like_count");
    group.member_count = jsonObject.optInt("member_count");
    group.description = jsonObject.optString("description");
    group.profile_image_url = jsonObject.optString("profile_image_url");
    group.createAtTime = jsonObject.optString("create_time", "");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonObject.length() > 0) {
        int length = jsonArray.length();
        group.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            group.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return group;
}

From source file:com.example.wcl.test_weiboshare.StatusList.java

public static StatusList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from w w  w .  j a  va  2s. co m

    StatusList statuses = new StatusList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        statuses.hasvisible = jsonObject.optBoolean("hasvisible", false);
        statuses.previous_cursor = jsonObject.optString("previous_cursor", "0");
        statuses.next_cursor = jsonObject.optString("next_cursor", "0");
        statuses.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("statuses");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            statuses.statusList = new ArrayList<Status>(length);
            for (int ix = 0; ix < length; ix++) {
                statuses.statusList.add(Status.parse(jsonArray.getJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return statuses;
}

From source file:com.heliosapm.opentsdb.client.opentsdb.OpenTsdbPutResponseHandler.java

/**
 * Extracts the failiure and success counts and the error json from the passed details response and increments the counters
 * @param responseCode The HTTP response code
 * @param content The response buffer // w w w .ja v a  2s  .co  m
 * @param log The logger to log with
 * @return the counts of failed submissions ([0]) and successful submissions ([1]).
 */
public static int[] doDetailedStats(final int responseCode, final ChannelBuffer content, final Logger log) {
    final int[] results = new int[] { 0, 0 };
    String contentStr = null;
    try {
        contentStr = content.toString(Constants.UTF8);
        if (responseCode == 400) {
            if (couldBeGzipIssue(responseCode, contentStr)) {
                log.error("Auto disabled http post gzip");
                HttpMetricsPoster.getInstance().autoDisableGZip();
            }
        }
        final JSONObject j = new JSONObject(contentStr);
        results[0] = j.getInt(FAILED_KEY);
        results[1] = j.getInt(SUCCESS_KEY);
        processErrors(j.optJSONArray(ERRORS_KEY), log);
    } catch (Exception ex) {
        log.warn("Failed to process response {}", contentStr, ex);
    }
    return results;
}

From source file:com.jennifer.ui.chart.widget.LegendWidget.java

private JSONArray getLegendIcon(JSONObject brushObject) {
    JSONArray arr = new JSONArray();
    JSONArray data = JSONUtil.clone(brushObject.getJSONArray("target"));

    if (key != null && key.length() > 0) {
        data = chart.data();//from  w w  w.ja  v  a  2 s.  c  om
    }

    int count = data.length();

    for (int i = 0; i < count; i++) {
        String text = "";

        if (key != null && key.length() > 0) {
            text = chart.series(key).optString("text", data.getJSONObject(i).getString(key));
        } else {
            String target = data.getString(i);
            text = chart.series(target).optString("text", target);
        }

        double rectWidth = (fontWidth - 4) * text.length();
        double width = Math.min(rectWidth, fontHeight);
        double height = width;

        Transform group = root.group(new JSONObject().put("class", "legend icon"));

        Transform rect = group.rect(new JSONObject().put("x", 0).put("y", 0).put("width", width)
                .put("height", height).put("fill", chart.color(i, brushObject.optJSONArray("colors"))));

        group.text(new JSONObject().put("x", width + 4).put("y", fontHeight - 3) // 3 is top, bottom font margin
                .put("font-family", chart.theme("fontFamily")).put("font-size", chart.theme("legendFontSize"))
                .put("fill", chart.theme("legendFontColor")).put("text-anchor", "start")).textNode(text);

        arr.put(new JSONObject().put("width", width + 4 + rectWidth + (i == count - 1 ? 0 : 10))
                .put("height", height + 4).put("icon", group)

        );

    }

    return arr;
}

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

public Logic(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();//from w ww.  jav  a 2 s.  c  om
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for the ones we want directly accessible
        if (!"conditions".equals(key) && !"conditionsType".equals(key) && !"trueActions".equals(key)
                && !"falseActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // initialise list
    _conditions = new ArrayList<Condition>();
    // grab conditions from json
    JSONArray jsonConditions = jsonAction.optJSONArray("conditions");

    // if we got some
    if (jsonConditions != null) {
        // loop them
        for (int i = 0; i < jsonConditions.length(); i++) {
            // add to our list
            _conditions.add(new Condition(jsonConditions.getJSONObject(i)));
        }
    }

    // get conditions type
    _conditionsType = jsonAction.getString("conditionsType");

    // grab any successActions
    JSONArray jsonTrueActions = jsonAction.optJSONArray("trueActions");
    // if we had some
    if (jsonTrueActions != null) {
        _trueActions = Control.getActions(rapidServlet, jsonTrueActions);
    }

    // grab any errorActions
    JSONArray jsonFalseActions = jsonAction.optJSONArray("falseActions");
    // if we had some
    if (jsonFalseActions != null) {
        // instantiate our contols collection
        _falseActions = Control.getActions(rapidServlet, jsonFalseActions);
    }

}