Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

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  w  ww.  j  a va 2s .c om
            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  ww. ja  v  a  2s . c o m
        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.appjma.appdeployer.service.Parser.java

public void parseApps(JSONObject json) throws JSONException {
    JSONArray items = JSONHelper.getJSONArrayOrEmtpy(json, "items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        parseApp(null, item);//from  w  w w. j av a2s  .  com
    }
    String nextToken = JSONHelper.getStrinOrNull(json, "next_token");
    mParserResult.setAppsNextToken(nextToken);
}

From source file:com.appjma.appdeployer.service.Parser.java

public void parseAppVersions(String appId, JSONObject json) throws JSONException {
    JSONArray items = JSONHelper.getJSONArrayOrEmtpy(json, "items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        parseAppVersion(appId, item);/*from w w w. ja v  a  2  s .c o  m*/
    }
}

From source file:de.jaetzold.philips.hue.HueBridgeComm.java

List<JSONObject> request(RM method, String fullPath, String json) throws IOException {
    final URL url = new URL(baseUrl, fullPath);
    log.fine("Request to " + method + " " + url + (json != null && json.length() > 0 ? ": " + json : ""));
    final URLConnection connection = url.openConnection();
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setRequestMethod(method.name());
        if (json != null && json.length() > 0) {
            if (method == RM.GET || method == RM.DELETE) {
                throw new HueCommException("Will not send json content for request method " + method);
            }// w  w w . j  ava2s  .  c o m
            httpConnection.setDoOutput(true);
            httpConnection.getOutputStream().write(json.getBytes(REQUEST_CHARSET));
        }
    } else {
        throw new IllegalStateException("The current baseUrl \"" + baseUrl + "\" is not http?");
    }

    final BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), REQUEST_CHARSET));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line).append('\n');
    }
    log.fine("Response from " + method + " " + url + ": " + builder);
    final String jsonString = builder.toString();
    List<JSONObject> result = new ArrayList<>();
    if (jsonString.trim().startsWith("{")) {
        result.add(new JSONObject(jsonString));
    } else {
        final JSONArray array = new JSONArray(jsonString);
        for (int i = 0; i < array.length(); i++) {
            result.add(array.getJSONObject(i));
        }
    }
    return result;
}

From source file:com.escapeir.server.Connect.java

@Override
protected Boolean doInBackground(Boolean... params) {
    HttpPost httppost = null;//from  w  ww  .j a v a  2 s .c  om
    // setOrGet = true is set user
    // setOrGet = false is Get user
    setOrGet = params[0];
    String urlExecute = "", urlSet = "http://escapeir.uphero.com/setUser.php",
            urlGet = "http://escapeir.uphero.com/getUser.php";
    String result = "";
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        if (setOrGet) {
            httppost = new HttpPost(urlSet);

            final ArrayList<NameValuePair> insertUser = new ArrayList<NameValuePair>();
            insertUser.add(new BasicNameValuePair("user", EscapeIRApplication.USER_NAME));
            insertUser.add(new BasicNameValuePair("time", EscapeIRApplication.USER_TIME));
            httppost.setEntity(new UrlEncodedFormEntity(insertUser));

        } else {
            httppost = new HttpPost(urlGet);

        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.i("Connect", "Connect");
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error in http connection " + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result = sb.toString();

        Log.i(EscapeIRApplication.TAG, "resultado");
        Log.i(EscapeIRApplication.TAG, result);
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error converting result " + e.toString());
    }
    // parse json data
    if (setOrGet) {
        // return if is set user
        return true;
    } else {
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                EscapeIRApplication.usersServer
                        .add(new User(json_data.getString("user"), json_data.getString("time")));
                Log.i(EscapeIRApplication.TAG,
                        "time: " + json_data.getString("time") + ", name: " + json_data.getString("user"));
            }
        } catch (JSONException e) {
            Log.e(EscapeIRApplication.TAG, "Error parsing data " + e.toString());
        }
    }
    return true;
}

From source file:com.liferay.mobile.android.v7.layoutrevision.LayoutRevisionService.java

public JSONObject addLayoutRevision(long userId, long layoutSetBranchId, long layoutBranchId,
        long parentLayoutRevisionId, boolean head, long plid, long portletPreferencesPlid,
        boolean privateLayout, String name, String title, String description, String keywords, String robots,
        String typeSettings, boolean iconImage, long iconImageId, String themeId, String colorSchemeId,
        String css, JSONObjectWrapper serviceContext) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from  ww  w.  j a va2 s. c  o m*/
        JSONObject _params = new JSONObject();

        _params.put("userId", userId);
        _params.put("layoutSetBranchId", layoutSetBranchId);
        _params.put("layoutBranchId", layoutBranchId);
        _params.put("parentLayoutRevisionId", parentLayoutRevisionId);
        _params.put("head", head);
        _params.put("plid", plid);
        _params.put("portletPreferencesPlid", portletPreferencesPlid);
        _params.put("privateLayout", privateLayout);
        _params.put("name", checkNull(name));
        _params.put("title", checkNull(title));
        _params.put("description", checkNull(description));
        _params.put("keywords", checkNull(keywords));
        _params.put("robots", checkNull(robots));
        _params.put("typeSettings", checkNull(typeSettings));
        _params.put("iconImage", iconImage);
        _params.put("iconImageId", iconImageId);
        _params.put("themeId", checkNull(themeId));
        _params.put("colorSchemeId", checkNull(colorSchemeId));
        _params.put("css", checkNull(css));
        mangleWrapper(_params, "serviceContext", "com.liferay.portal.kernel.service.ServiceContext",
                serviceContext);

        _command.put("/layoutrevision/add-layout-revision", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:me.tassoevan.cordova.BackgroundPlugin.java

private boolean doConfigureAction(JSONArray args, CallbackContext callbackContext) throws JSONException {
    settings = args.getJSONObject(0);

    if (isBind) {
        stopService();//  ww w.  j a va 2 s. co m
        startService();
    }

    callbackContext.success();
    return true;
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {/*from   w ww.j a v a2s . c  om*/
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}

From source file:com.df.app.carsWaiting.CarsWaitingListActivity.java

/**
 * //from  ww w  .  j a  va2 s. c om
 * @param result
 */
private void fillInData(String result) {
    try {
        JSONArray jsonArray = new JSONArray(result);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            CarsWaitingItem item = new CarsWaitingItem();
            item.setPlateNumber(jsonObject.getString("plateNumber"));
            item.setExteriorColor(jsonObject.getString("exteriorColor"));
            item.setCarType(jsonObject.getString("licenseModel"));
            item.setDate(jsonObject.getString("createDate"));
            item.setCarId(jsonObject.getInt("carId"));
            item.setJsonObject(jsonObject);

            data.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    adapter.notifyDataSetChanged();

    startNumber = data.size() + 1;

    if (data.size() == 0) {
        footerView.setVisibility(View.GONE);
    } else {
        footerView.setVisibility(View.VISIBLE);
    }

    //        for(int i = 0; i < data.size(); i++)
    //            swipeListView.closeAnimate(i);

    //        // 0, ??(?
    //        if(data.size() == 0) {
    //            DeleteFiles.deleteFiles(AppCommon.photoDirectory);
    //            DeleteFiles.deleteFiles(AppCommon.savedDirectory);
    //        }
}