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.rsimiao.exemplosloopj.UsuarioWS.java

public void buscar(final Handler handler) {

    try {/*from  w ww  .  j  av  a  2s.  c om*/
        RequestParams parametros = new RequestParams();
        parametros.add("limite", "todos");

        Wscliente.post(url, parametros, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(int code, Header[] header, byte[] conteudo, Throwable arg3) {
                //voc pode colocar aqui seu tratamento de erro
                Log.d("WS USUARIO", "DEU ERRO");
                Message msg = new Message();
                msg.what = 0; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro.
                handler.sendMessage(msg);
            }

            @Override
            public void onSuccess(int code, Header[] header, byte[] conteudo) {
                try {
                    JSONObject json = new JSONObject(new String(conteudo));
                    List<Usuario> usuarios = new ArrayList<Usuario>();
                    //sua lgica para tratar o json recebido (no precisa ser desse modo jurstico)
                    if (json.has("status") && json.getString("status").equalsIgnoreCase("success")) {

                        JSONArray jUsrs = json.getJSONArray("usuarios");

                        for (int i = 0; i < jUsrs.length(); i++) {
                            Usuario u = new Usuario();
                            u.setNome(jUsrs.getJSONObject(i).getString("nome"));
                            u.setUsuario(jUsrs.getJSONObject(i).getString("usuario"));
                            u.setLogged(jUsrs.getJSONObject(i).getBoolean("islogged"));
                            usuarios.add(u);
                        }

                        Message msg = new Message();
                        msg.what = 1; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro.
                        msg.obj = usuarios;
                        handler.sendMessage(msg);

                    }

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

            }

        });

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

}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Gets the last completed thermostat job.
 * /*from w w  w  . j av  a2 s .  c om*/
 * @param thermostatId
 *            the thermostat id
 * @return the last completed thermostat job
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#getLastCompletedThermostatJob(java.lang.Integer)
 */
@Override
public ThermostatJob getLastCompletedThermostatJob(Integer thermostatId) {

    ThermostatJob thermostatJob = null;
    JSONArray jsonArray = getJobData(thermostatId);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            thermostatJob = new ThermostatJob();
            Calendar calendar = DateUtil.getUTCCalendar();
            JSONObject jsonObj = jsonArray.getJSONObject(i);

            thermostatJob.setThermostatId(thermostatId);
            thermostatJob.setJobData(jsonObj.toString());

            thermostatJob.setStartDate(calendar);
            thermostatJob.setEndDate(calendar);

            thermostatJob.setJobType("SPO");
            thermostatJob.setAlgorithmId(190);
            thermostatJob.setJobStatus(ThermostatJob.Status.PROCESSED);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return thermostatJob;
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Checks if is sPO block active.//ww w  .  j a v  a2  s  .  c  o  m
 * 
 * @param thermostatId
 *            the thermostat id
 * @param algoId
 *            the algo id
 * @return true, if is sPO block active
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#isSPOBlockActive(java.lang.Integer,
 *      int)
 */
@Override
public boolean isSPOBlockActive(Integer thermostatId, int algoId) {

    log("Check if SPO is active for thermostat :" + thermostatId, true);
    boolean spoActive = false;
    Thermostat thermostat = findBythermostatId(thermostatId);
    Calendar currentTime = (Calendar) Calendar.getInstance(TimeZone.getTimeZone(thermostat.getTimezone()))
            .clone();

    JSONArray jsonArray = getJobData(thermostatId);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Calendar startCal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("start"),
                    thermostat.getTimezone());
            Calendar endcal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("end"),
                    thermostat.getTimezone());

            if (currentTime.after(startCal) && currentTime.before(endcal)) {
                spoActive = true;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return spoActive;
}

From source file:drusy.ui.panels.WifiStatePanel.java

public void update(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_WIFI_ID, output,
            "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override/*  w w  w. ja  v  a  2 s.c  o m*/
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONArray result = obj.getJSONArray("result");
                JSONObject wifi = result.getJSONObject(0);
                int id = wifi.getInt("id");

                addUsersForWifiId(id, updater);

            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get id)", msg);
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get id)", ex.getMessage());
        }
    });
}

From source file:drusy.ui.panels.WifiStatePanel.java

public void addUsersForWifiId(int id, final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_WIFI_STATIONS.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override// w w w  .j a  v a  2s . co  m
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                final JSONArray usersList = obj.getJSONArray("result");

                for (int i = 0; i < usersList.length(); ++i) {
                    JSONObject user = usersList.getJSONObject(i);
                    final String hostname = user.getString("hostname");
                    final long txBytes = user.getLong("tx_rate");
                    final long rxBytes = user.getLong("rx_rate");
                    JSONObject host = user.getJSONObject("host");
                    final String host_type = host.getString("host_type");

                    addUser(host_type, hostname, txBytes, rxBytes);
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get users)", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get users)", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java

public static List<TranslationInfo> toTranslationList(JSONArray jsonArray) throws Exception {
    final int length = jsonArray.length();
    final List<TranslationInfo> translations = new ArrayList<TranslationInfo>(length);
    for (int i = 0; i < length; ++i) {
        final JSONObject translationObject = jsonArray.getJSONObject(i);
        final String name = translationObject.getString("name");
        final String shortName = translationObject.getString("shortName");
        final String language = translationObject.getString("language");
        final String blobKey = translationObject.optString("blobKey", null);
        final int size = translationObject.getInt("size");
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(shortName) || TextUtils.isEmpty(language)
                || size <= 0) {// w ww .j ava 2 s.co  m
            throw new Exception("Illegal translation info.");
        }
        translations.add(new TranslationInfo(name, shortName, language, blobKey, size));
    }
    return translations;
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.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  ww.  ja  v a 2s  .  c o  m*/
 */
public String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationQuery)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

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

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

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

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // 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);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.java

/**
 * Given a string of the form returned by the api call:
 * http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
 * retrieve the maximum temperature for the day indicated by dayIndex
 * (Note: 0-indexed, so 0 would refer to the first day).
 *//*ww w  .ja  v  a  2 s.c o  m*/
private static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex) throws JSONException {
    JSONObject data = new JSONObject(weatherJsonStr);
    JSONArray days = data.getJSONArray("list");
    JSONObject dayJson = days.getJSONObject(dayIndex);
    JSONObject temp = dayJson.getJSONObject("temp");
    return temp.getDouble("max");
}

From source file:com.liferay.mobile.android.v62.phone.PhoneService.java

public JSONObject addPhone(String className, long classPK, String number, String extension, int typeId,
        boolean primary) throws Exception {
    JSONObject _command = new JSONObject();

    try {/* w  w  w .j  a va  2s. c o  m*/
        JSONObject _params = new JSONObject();

        _params.put("className", checkNull(className));
        _params.put("classPK", classPK);
        _params.put("number", checkNull(number));
        _params.put("extension", checkNull(extension));
        _params.put("typeId", typeId);
        _params.put("primary", primary);

        _command.put("/phone/add-phone", _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:com.liferay.mobile.android.v62.phone.PhoneService.java

public JSONObject addPhone(String className, long classPK, String number, String extension, int typeId,
        boolean primary, JSONObjectWrapper serviceContext) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from   w  w w. ja  v a  2 s .  c om
        JSONObject _params = new JSONObject();

        _params.put("className", checkNull(className));
        _params.put("classPK", classPK);
        _params.put("number", checkNull(number));
        _params.put("extension", checkNull(extension));
        _params.put("typeId", typeId);
        _params.put("primary", primary);
        mangleWrapper(_params, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);

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

    JSONArray _result = session.invoke(_command);

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

    return _result.getJSONObject(0);
}