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:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private JSONArray adjustTimeAndTipiSpecifici(String dataAsCSV) throws ParseException {
    JSONArray jsonArray = CDL.toJSONArray(dataAsCSV);
    int length = jsonArray.length();
    JSONArray jsonArrayNew = new JSONArray();
    for (int i = 0; i < length; i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        JSONObject jsonObjectNew = new JSONObject();

        jsonObjectNew.put("nome", jsonObject.getString("nome"));
        jsonObjectNew.put("indirizzo", jsonObject.getString("indirizzo"));
        jsonObjectNew.put("numeroCivico", jsonObject.getString("numero-civico"));
        jsonObjectNew.put("cap", jsonObject.getString("cap"));
        jsonObjectNew.put("quartiere", jsonObject.getString("quartiere"));
        jsonObjectNew.put("citta", jsonObject.getString("citta"));
        jsonObjectNew.put("geolocazione", jsonObject.getString("geolocazione"));
        jsonObjectNew.put("telefono", jsonObject.getString("telefono"));
        jsonObjectNew.put("mobile", jsonObject.getString("mobile"));
        jsonObjectNew.put("email", jsonObject.getString("email"));
        jsonObjectNew.put("web", jsonObject.getString("web"));
        jsonObjectNew.put("tipi", jsonObject.getString("tipi"));
        jsonObjectNew.put("tipiSpecifici", jsonObject.getString("tipi-specifici"));

        //         jsonObjectNew.put("tipiSpecificiReduced", getTipiReduced(jsonObject));
        //         jsonObjectNew.put("times", getTimes(jsonObject));

        LinkedList<String> date = findNumbers(jsonObject.getString("luogo-da-visitare.informazioni_storiche"));
        String dateString = date.toString().replace("[", "").replace("]", "");
        jsonObjectNew.put("luoghiDaVisitare.informazioniStoriche.date", dateString);

        jsonArrayNew.put(jsonObjectNew);
    }/* w  w  w  .j  a  v  a2 s  . c om*/
    return jsonArrayNew;
}

From source file:mr.robotto.engine.loader.components.skeleton.MrSkeletonLoader.java

private Map<String, MrBone> loadPose() throws JSONException {
    JSONArray poseJson = mRoot.getJSONArray("Pose");
    Map<String, MrBone> bones = new HashMap<String, MrBone>();
    for (int i = 0; i < poseJson.length(); i++) {
        MrBoneLoader boneLoader = new MrBoneLoader(poseJson.getJSONObject(i));
        MrBone bone = boneLoader.parse();
        bones.put(bone.getName(), bone);
    }//from   w  ww.jav  a2  s. c o  m
    return bones;
}

From source file:mr.robotto.engine.loader.components.skeleton.MrSkeletonLoader.java

private Map<String, MrSkeletalAction> loadActions() throws JSONException {
    JSONArray actionsJson = mRoot.getJSONArray("Actions");
    Map<String, MrSkeletalAction> actions = new HashMap<String, MrSkeletalAction>();
    for (int i = 0; i < actionsJson.length(); i++) {
        MrSkeletalActionLoader loader = new MrSkeletalActionLoader(actionsJson.getJSONObject(i));
        MrSkeletalAction action = loader.parse();
        actions.put(action.getName(), action);
    }//from  ww  w  .j  av a 2s .  c  o  m
    return actions;
}

From source file:com.android.talkback.tutorial.Tutorial.java

public Tutorial(Context context, JSONObject tutorial) throws JSONException {
    JSONArray lessons = JsonUtils.getJsonArray(tutorial, JSON_KEY_LESSONS);
    if (lessons != null && lessons.length() > 0) {
        int lessonCount = lessons.length();
        mLessons = new TutorialLesson[lessonCount];
        for (int i = 0; i < lessonCount; i++) {
            JSONObject lesson = lessons.getJSONObject(i);
            mLessons[i] = new TutorialLesson(context, lesson);
        }//w  w  w .  j  a va2 s  . c o  m
    } else {
        mLessons = new TutorialLesson[0];
    }
}

From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworksListParser.java

public BikeNetworksListParser(String toParse) throws ParseException {
    bikeNetworks = new ArrayList<>();

    try {/* w ww.ja  va2s.  co m*/
        JSONObject jsonObject = new JSONObject(toParse);
        JSONArray rawNetworks = jsonObject.getJSONArray("networks");
        for (int i = 0; i < rawNetworks.length(); i++) {
            JSONObject rawNetwork = rawNetworks.getJSONObject(i);

            String id = rawNetwork.getString("id");
            String name = rawNetwork.getString("name");
            String company = rawNetwork.getString("company");
            BikeNetworkLocation location;

            /* network location */
            {
                JSONObject rawLocation = rawNetwork.getJSONObject("location");

                double latitude = rawLocation.getDouble("latitude");
                double longitude = rawLocation.getDouble("longitude");
                String city = rawLocation.getString("city");
                String country = rawLocation.getString("country");

                location = new BikeNetworkLocation(latitude, longitude, city, country);

            }
            bikeNetworks.add(new BikeNetworkInfo(id, name, company, location));
        }
    } catch (JSONException e) {
        throw new ParseException("Error parsing JSON", 0);
    }
}

From source file:com.github.koraktor.steamcondenser.community.AppNews.java

/**
 * Loads the news for the given game with the given restrictions
 *
 * @param appId The unique Steam Application ID of the game (e.g.
 *        <code>440</code> for Team Fortress 2). See
 *        http://developer.valvesoftware.com/wiki/Steam_Application_IDs for
 *        all application IDs/*  ww  w  .j  ava 2s  .c  om*/
 * @param count The maximum number of news to load (default: 5). There's no
 *        reliable way to load all news. Use really a really great number
 *        instead
 * @param maxLength The maximum content length of the news (default: nil).
 *        If a maximum length is defined, the content of the news will only
 *        be at most <code>maxLength</code> characters long plus an
 *        ellipsis
 * @return A list of news for the specified game with the given options
 * @throws WebApiException if a request to Steam's Web API fails
 */
public static List<AppNews> getNewsForApp(int appId, int count, Integer maxLength) throws WebApiException {
    try {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("appid", appId);
        params.put("count", count);
        params.put("maxlength", maxLength);
        JSONObject data = new JSONObject(WebApi.getJSON("ISteamNews", "GetNewsForApp", 2, params));

        List<AppNews> newsItems = new ArrayList<AppNews>();
        JSONArray newsData = data.getJSONObject("appnews").getJSONArray("newsitems");
        for (int i = 0; i < newsData.length(); i++) {
            newsItems.add(new AppNews(appId, newsData.getJSONObject(i)));
        }

        return newsItems;
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

From source file:com.abeo.tia.noordin.AddCaseStep2of4.java

public void dropdownBankDeveloperSolicitor() {

    RequestParams params = null;//from  w  ww  . ja  v  a  2s .c  o m
    params = new RequestParams();

    RestService.post(METHOD_PROPERTY_BDS_DROPDOWN, params, new BaseJsonHttpResponseHandler<String>() {

        @Override
        public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) {
            // TODO Auto-generated method stub
            System.out.println(arg3);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) {
            // TODO Auto-generated method stub
            System.out.println("Property Activity GetDropdown Success Details ");
            try {
                // Create new list
                jsonlistBank = new ArrayList<HashMap<String, String>>();
                jsonlistDeveloper = new ArrayList<HashMap<String, String>>();
                jsonlistSolicitor = new ArrayList<HashMap<String, String>>();

                jsonResponse = new JSONObject(arg2);

                JSONArray jsonBank = jsonResponse.getJSONArray("Bank");
                for (int j = 0; j < jsonBank.length(); j++) {
                    JSONObject bank = jsonBank.getJSONObject(j);

                    id_b = bank.getString("BankCode").toString();
                    name_b = bank.getString("BankName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> bankList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON BANK LIST");
                    bankList.put("Id_T", id_b);
                    System.out.println(name);
                    bankList.put("Name_T", name_b);
                    System.out.println(name);
                    System.out.println(" END SEND JSON BANK LIST");

                    jsonlistBank.add(bankList);
                    System.out.println("JSON BANK LIST");
                    System.out.println(jsonlistProject);

                }

                // Spinner set Array Data in Drop down

                sAdapBANK = new SimpleAdapter(AddCaseStep2of4.this, jsonlistBank, R.layout.spinner_item,
                        new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyLSTCHG_BANKNAME.setAdapter(sAdapBANK);

                for (int j = 0; j < jsonlistBank.size(); j++) {
                    if (jsonlistBank.get(j).get("Name_T").equals(bankDetailResponse)) {
                        spinnerpropertyLSTCHG_BANKNAME.setSelection(j);
                        break;
                    }
                }

                JSONArray jsonDeveloper = jsonResponse.getJSONArray("Developer");
                for (int j = 0; j < jsonDeveloper.length(); j++) {
                    JSONObject dev = jsonDeveloper.getJSONObject(j);
                    id = dev.getString("DevCode").toString();
                    name = dev.getString("DevName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> devList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON DEV LIST");
                    devList.put("Id_B", id);
                    System.out.println(name);
                    devList.put("Name_B", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON DEV LIST");

                    jsonlistDeveloper.add(devList);
                    System.out.println("JSON DEV LIST");
                    System.out.println(jsonlistDeveloper);

                }
                // Spinner set Array Data in Drop down

                sAdapDEV = new SimpleAdapter(AddCaseStep2of4.this, jsonlistDeveloper, R.layout.spinner_item,
                        new String[] { "Id_B", "Name_B" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyDEVELOPER.setAdapter(sAdapDEV);

                for (int j = 0; j < jsonlistDeveloper.size(); j++) {
                    if (jsonlistDeveloper.get(j).get("Id_B").equals(developerCodeResponse)) {
                        spinnerpropertyDEVELOPER.setSelection(j);
                        break;
                    }
                }

                JSONArray jsonSolicitor = jsonResponse.getJSONArray("Solicitor");
                for (int j = 0; j < jsonSolicitor.length(); j++) {
                    JSONObject solic = jsonSolicitor.getJSONObject(j);
                    id = solic.getString("SoliCode").toString();
                    name = solic.getString("SoliName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> solicList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON SOLICITOR LIST");
                    solicList.put("Id_T", id);
                    System.out.println(name);
                    solicList.put("Name_T", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON SOLICITOR LIST");

                    jsonlistSolicitor.add(solicList);
                    System.out.println("JSON SOLICITOR LIST");
                    System.out.println(jsonlistSolicitor);
                }

                // Spinner set Array Data in Drop down
                sAdapSOLIC = new SimpleAdapter(AddCaseStep2of4.this, jsonlistSolicitor, R.layout.spinner_item,
                        new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyDEVSOLICTOR.setAdapter(sAdapSOLIC);

                for (int j = 0; j < jsonlistSolicitor.size(); j++) {
                    if (jsonlistSolicitor.get(j).get("Id_T").equals(devSolictorCodeResponse)) {
                        spinnerpropertyDEVSOLICTOR.setSelection(j);
                        break;
                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println(arg2);

        }

        @Override
        protected String parseResponse(String arg0, boolean arg1) throws Throwable {
            // Get Json response

            System.out.println("Property GetDropdown parse Response");
            System.out.println(arg0);
            return null;
        }

    });

}

From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java

/** {@inheritDoc} */
@Override//w  w  w.jav  a  2  s. c  o  m
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(drinkUri).build());
            batch.add(ContentProviderOperation.newDelete(drinkKegUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Drinks.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

            // Inherit starred value from previous row
            if (values.containsKey(Drinks.DRINK_STARRED)) {
                builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED));
            }

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

            // Normal session details ready, write to provider
            batch.add(builder.build());

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build());
            }
        }
    }

    return batch;
}

From source file:org.liberty.android.fantastischmemo.downloader.FEDirectory.java

private List<DownloadItem> retrieveList() throws Exception {
    List<DownloadItem> diList = new ArrayList<DownloadItem>();
    String url = FE_API_DIRECTORY;
    String jsonString = downloaderUtils.downloadJSONString(url);
    JSONObject jsonObject = new JSONObject(jsonString);
    String status = jsonObject.getString("response_type");
    Log.v(TAG, "JSON String: " + jsonString);
    if (!status.equals("ok")) {
        Log.v(TAG, "JSON String: " + jsonString);
        throw new IOException("Status is not OK. Status: " + status);
    }//from w  w  w.  j a  v a  2  s. c o m
    JSONArray directoryArray = jsonObject.getJSONArray("results");
    /*
     * Each result has tags which is an array containing
     * tags and a string of tag group title
     */
    for (int i = 0; i < directoryArray.length(); i++) {
        JSONArray tagsArray = directoryArray.getJSONObject(i).getJSONArray("tags");
        for (int j = 0; j < tagsArray.length(); j++) {
            JSONObject jsonItem = tagsArray.getJSONObject(j);
            String s = jsonItem.getString("tag");
            DownloadItem di = new DownloadItem(DownloadItem.ItemType.Database, s, "", "");
            di.setType(DownloadItem.ItemType.Category);
            diList.add(di);
        }
    }
    return diList;
}

From source file:org.brickred.socialauth.provider.HotmailImpl.java

private List<Contact> getContacts(final String url) throws Exception {
    Response serviceResponse;//from   w w  w.  j  a v  a2  s. c o m
    try {
        serviceResponse = authenticationStrategy.executeFeed(url);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + url, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException(
                "Error while getting contacts from " + url + "Status : " + serviceResponse.getStatus());
    }
    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new ServerDataException("Failed to get response from " + url, e);
    }
    LOG.debug("User Contacts list in JSON " + result);
    JSONObject resp = new JSONObject(result);
    List<Contact> plist = new ArrayList<Contact>();
    if (resp.has("data")) {
        JSONArray addArr = resp.getJSONArray("data");
        LOG.debug("Contacts Found : " + addArr.length());
        for (int i = 0; i < addArr.length(); i++) {
            JSONObject obj = addArr.getJSONObject(i);
            Contact p = new Contact();
            if (obj.has("email_hashes")) {
                JSONArray emailArr = obj.getJSONArray("email_hashes");
                if (emailArr.length() > 0) {
                    p.setEmailHash(emailArr.getString(0));
                }
            }
            if (obj.has("name")) {
                p.setDisplayName(obj.getString("name"));
            }
            if (obj.has("first_name")) {
                p.setFirstName(obj.getString("first_name"));
            }
            if (obj.has("last_name")) {
                p.setLastName(obj.getString("last_name"));
            }
            if (obj.has("id")) {
                p.setId(obj.getString("id"));
            }
            plist.add(p);
        }
    }
    serviceResponse.close();
    return plist;
}