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.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertWeatherData(String data, SQLiteDatabase db) {
    try {/*from ww  w  .  j ava 2 s.  c  o  m*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject array = jsonArray.getJSONObject(i);
            JSONObject jsonObject = array.getJSONObject("weather");

            long timestamp = jsonObject.getLong("timestamp");
            int year = jsonObject.getInt("year");
            int month = jsonObject.getInt("month");
            int day = jsonObject.getInt("day");
            int max_temp_c = jsonObject.getInt("max_temp_c");
            int max_temp_f = jsonObject.getInt("max_temp_f");
            int min_temp_c = jsonObject.getInt("min_temp_c");
            int min_temp_f = jsonObject.getInt("min_temp_f");
            int wind_speed_miles = jsonObject.getInt("wind_speed_miles");
            int wind_speed_km = jsonObject.getInt("wind_speed_km");
            String wind_direction = jsonObject.getString("wind_direction");
            int wind_degree = jsonObject.getInt("wind_degree");
            String icon_url = jsonObject.getString("icon_url");
            String description = jsonObject.getString("weather_description");
            Double precipitation = jsonObject.getDouble("precipitation");

            String inS = "INSERT INTO weather VALUES(" + timestamp + "," + year + "," + month + "," + day + ","
                    + max_temp_c + "," + max_temp_f + "," + min_temp_c + "," + min_temp_f + ","
                    + wind_speed_miles + "," + wind_speed_km + ",'" + wind_direction + "'," + wind_degree + ",'"
                    + icon_url + "','" + description + "'," + precipitation + ")";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertSurfData(String data, SQLiteDatabase db) {
    /* Delete any current versions with the same request timestamps */
    try {/*from   w  ww  .ja va2s. co m*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp"));
        }
    } catch (Exception e) {
        System.err.println("Could not delete data");
    }

    /* Now actually do the inserts! */
    try {
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            int location = surf.getInt("location");
            long timestamp = surf.getLong("timestamp");
            long localtime = surf.getLong("local_time");
            int year = surf.getInt("year");
            int month = surf.getInt("month");
            int day = surf.getInt("day");
            int hour = surf.getInt("hour");
            int minute = surf.getInt("minute");
            int faded_rating = surf.getInt("faded_rating");
            int solid_rating = surf.getInt("solid_rating");
            double min_surf = surf.getDouble("min_surf_height");
            double abs_min_surf = surf.getDouble("abs_min_surf_height");
            double max_surf = surf.getDouble("max_surf_height");
            double abs_max_surf = surf.getDouble("abs_max_surf_height");
            double swell_height = surf.getDouble("swell_height");
            double swell_period = surf.getDouble("swell_period");
            double swell_angle = surf.getDouble("swell_angle");
            String swell_direction = surf.getString("swell_direction");
            String swell_chart_url = surf.getString("swell_chart");
            String period_chart_url = surf.getString("period_chart");
            String wind_chart_url = surf.getString("wind_chart");
            String pressure_chart_url = surf.getString("pressure_chart");
            String sst_chart_url = surf.getString("sst_chart");

            String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year
                    + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + ","
                    + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf
                    + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction
                    + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','"
                    + pressure_chart_url + "','" + sst_chart_url + "')";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

From source file:com.jsonstore.api.JSONStoreFindOptions.java

/**
 * @exclude Used internally/*from  ww  w  .  ja va  2  s  .c  o m*/
 */
public JSONStoreFindOptions(JSONObject options) throws JSONException, JSONStoreInvalidSortObjectException {

    filter = new HashMap<String, Boolean>();
    sort = new LinkedHashMap<String, SortDirection>();

    String limitStr = options.optString(JSONStoreFindOptions.OPTION_LIMIT, null);
    if (limitStr != null) {
        Integer limitParse = Integer.parseInt(limitStr);
        setLimit(limitParse);
    }

    String offsetStr = options.optString(JSONStoreFindOptions.OPTION_OFFSET, null);
    if (offsetStr != null) {
        Integer offsetParse = Integer.parseInt(offsetStr);
        setOffset(offsetParse);
    }

    JSONArray sortArray = options.optJSONArray(JSONStoreFindOptions.OPTION_SORT_ARRAY);
    if (sortArray != null) {
        for (int idx = 0; idx < sortArray.length(); idx++) {
            JSONObject sortObject = sortArray.getJSONObject(idx);

            Iterator<String> keys = sortObject.keys();
            String key = keys.next();

            if (keys.hasNext()) {
                throw new JSONStoreInvalidSortObjectException(
                        "One of the sort objects in the sort array has more than one field.");
            }

            //Parse the direction of the sort for this search field:
            String sortDirectionStr = sortObject.getString(key);
            if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.ASCENDING)) {
                sortBySearchFieldAscending(key);
            } else if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.DESCENDING)) {
                sortBySearchFieldDescending(key);
            } else {
                throw new JSONStoreInvalidSortObjectException(
                        "Invalid sorting direction (ascending or descending) specified.");
            }
        }

    }

    JSONArray filterParse = options.optJSONArray(JSONStoreFindOptions.OPTION_FILTER);
    if (filterParse != null) {
        for (int idx = 0; idx < filterParse.length(); idx++) {
            addSearchFilter(filterParse.getString(idx));
        }
    }
}

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

/**
 * Gets the list of followers of the user and their screen name.
 * //w ww.  j a v  a 2 s.  c  om
 * @return List of contact objects representing Contacts. Only name, screen
 *         name and profile URL will be available
 */
@Override
public List<Contact> getContactList() throws Exception {
    if (!isVerify) {
        throw new SocialAuthException("Please call verifyResponse function first to get Access Token");
    }
    String url = CONTACTS_URL;
    List<Contact> plist = new ArrayList<Contact>();
    LOG.info("Fetching contacts from " + url);
    Response serviceResponse = null;
    try {
        serviceResponse = authenticationStrategy.executeFeed(url);
    } catch (Exception ie) {
        throw new SocialAuthException("Failed to retrieve the contacts from " + url, ie);
    }
    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new ServerDataException("Failed to get response from " + url);
    }
    try {
        LOG.debug("User Contacts list in json : " + result);
        JSONArray data = new JSONArray(result);
        LOG.debug("Found contacts : " + data.length());
        for (int i = 0; i < data.length(); i++) {
            JSONObject obj = data.getJSONObject(i);
            Contact p = new Contact();
            String name = obj.getString("name");
            if (name != null) {
                String nameArr[] = name.split(" ");
                if (nameArr.length > 1) {
                    p.setFirstName(nameArr[0]);
                    p.setLastName(nameArr[1]);
                } else {
                    p.setFirstName(obj.getString("name"));
                }
                p.setDisplayName(name);
            }
            p.setId(obj.getString("profile_id"));
            plist.add(p);
        }
    } catch (Exception e) {
        throw new ServerDataException("Failed to parse the user friends json : " + result, e);
    }
    return plist;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }/*from  w  w  w  . j  a v  a2 s  .  c o m*/

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

From source file:com.appdynamics.demo.gasp.fragment.TwitterResponderFragment.java

private static List<String> getTweetsFromJson(String json) {
    ArrayList<String> tweetList = new ArrayList<String>();

    try {// w w w.jav  a 2s.  c  o m
        JSONObject tweetsWrapper = (JSONObject) new JSONTokener(json).nextValue();
        JSONArray tweets = tweetsWrapper.getJSONArray("statuses");

        for (int i = 0; i < tweets.length(); i++) {
            JSONObject tweet = tweets.getJSONObject(i);
            Log.d(TAG, "Tweet: " + tweet.getString("text"));
            tweetList.add(tweet.getString("text"));
        }
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse JSON.", e);
    }

    return tweetList;
}

From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java

/**
 * Parses the JSON-String to a list of {@link Muscle}s.
 * /*ww  w  . j a  va 2  s  .c o  m*/
 * Example for such a .json File:
 * 
 *  [{
  *     "de": { "name" : "Bizeps" },
  *     "en": { "name" : "Biceps", "alternative_names":["Biceps muscle"] }
  *   }, ...]
  *   
  * @param jsonString The String to parse.
  * 
  * @return A list of {@link Muscle}s, null if an Error occurs..
  * 
 */
@Override
public List<Muscle> parse(String jsonString) {
    List<Muscle> muscleList = new ArrayList<Muscle>();

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);

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

            Muscle m = null;

            for (String locale : TAG_LOCALES) {
                if (muscleObject.has(locale)) {
                    JSONObject languageObject = muscleObject.getJSONObject(locale);

                    // name
                    String name = languageObject.getString(TAG_NAME);

                    // first name is primary name, all other names are alternative names
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(name);

                    // alternative names   
                    if (languageObject.has(TAG_ALTERNATIVE_NAMES)) {
                        JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES);
                        String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray);

                        for (int t = 0; t < alternativeNameArray.length; t++) {
                            String altName = alternativeNameArray[t];
                            nameList.add(altName);
                        }
                    }

                    if (m == null) {
                        m = new Muscle(new Locale(locale), nameList);
                    } else {
                        m.addNames(new Locale(locale), nameList);
                    }
                }
            }

            // Log.d(TAG, "Finished parsing Muscle: \n" + m.toDebugString());
            muscleList.add(m);

        }

    } catch (JSONException e) {
        Log.e(TAG, "Error during parsing JSON File.", e);
        return null;
    }

    if (muscleList.isEmpty())
        throw new AssertionError("JSON parsing failed: no muscles parsed.");
    return muscleList;
}

From source file:com.util.httpRecargas.java

public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) {

    //   System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;//from www.java 2  s.c  o  m
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje);
    //   System.out.println(" el objeto jdata es " + jdata);
    objJason = new JSONObject(jdata);
    // System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());
    /*
            List<String> list = new ArrayList<String>();
            for (int i = 0; i
        < jsonArray.length(); i++) {
    list.add(String.valueOf(i));
    list.add(jsonArray.getJSONObject(i).getString("created_date"));
    list.add(jsonArray.getJSONObject(i).getString("description"));
    list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
    list.add(jsonArray.getJSONObject(i).getString("before_balance"));
    list.add(jsonArray.getJSONObject(i).getString("after_balance"));
            }
            System.out.println("\n\nel array java contiene "+ list.toString());
    */
    List<Recarga> recargas = new ArrayList<Recarga>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Recarga recarga = new Recarga();
        recarga.setNo(i);
        recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date"));
        recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description"));
        recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
        recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance"));
        recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance"));

        recargas.add(recarga);
    }

    for (int i = 0; i < recargas.size(); i++) {
        System.out.print("\n\nNo" + recargas.get(i).getNo());
        System.out.print("\nFecna " + recargas.get(i).getFecha());
        System.out.print("\nDescripcion " + recargas.get(i).getDescripcion());
        System.out.print("\nMonto " + recargas.get(i).getMonto());
        System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior());
        System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior());

    }
    return recargas;

}

From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java

private void parsePagePosts(GraphObject result, FacebookRequestError error) {
    String title = null;// w  w  w .  ja  va2 s  .  c o  m
    String alertMessage = null;

    if (error == null) {
        Log.d("facebookfoo ###############", "retrievig posts success");
        try {
            JSONArray page_posts = result.getInnerJSONObject().getJSONArray("data");

            Log.d("facebookfoo ###############", "retrievig user posts length : " + page_posts.length());

            for (int i = 0; i < page_posts.length(); i++) {
                Log.d("facebookfoo ##############", "post id : " + i);
                JSONObject item = page_posts.getJSONObject(i);
                String post_id = item.getString("id");
                //Log.d("facebookfoo ##############", "post id : " + post_id);
                String story = item.getString("story");
                //Log.d("facebookfoo ##############","story : " + story);
                String message = item.getString("type");
                //Log.d("facebookfoo ##############","type : " + message);
                String updated_time = item.getString("updated_time");
                // Log.d("facebookfoo ##############","updated_time : " + updated_time);
                //boolean ispublished = item.getString("")
                if (!postsTable.containsKey(post_id)) {
                    postsTable.put(post_id, new PostsRecord(post_id, story, message, updated_time, true));
                }

                // Log.d("facebookfoo ##############","is_published : " + );

            }
        } catch (Exception e) {
        }

    } else {
        Log.d("facebookfoo ###############", "retrievig page posts fail");
    }

}

From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java

private void parseUserPages(GraphObject result, FacebookRequestError error) {
    String title = null;/* w ww  .j  a  v  a 2s .  com*/
    String alertMessage = null;

    if (error == null) {
        Log.d("facebookfoo ###############", "retrievig user pages success");
        try {
            JSONArray user_pages = result.getInnerJSONObject().getJSONArray("data");

            for (int i = 0; i < user_pages.length(); i++) {
                JSONObject item = user_pages.getJSONObject(i);
                page_id = item.getString("id");
                Log.d("facebookfoo ##############", "id : " + page_id);
                Log.d("facebookfoo ##############", "category : " + item.getString("category"));
                Log.d("facebookfoo ##############", "perms : " + item.getString("perms"));
                String accessToken = item.getString("access_token");

                if (accessToken != null) {
                    Log.d("facebookfoo ##############", "access_token : " + accessToken);
                    Session session = Session.getActiveSession();
                    AccessToken currentToken = session.getTokenInfo();
                    /*[NJ] Need to use the page access token in the session, with a couple of changes in the facebook sdk
                     1. make setTokenInfo public
                     2. Make AccessToken pubic
                    */
                    session.setTokenInfo(new AccessToken(accessToken, currentToken.getExpires(),
                            currentToken.getPermissions(), currentToken.getDeclinedPermissions(),
                            currentToken.getSource(), currentToken.getLastRefresh()));

                }

            }
        } catch (Exception e) {
        }

    } else {
        Log.d("facebookfoo ###############", "retrievig user pages fail");
    }

}