Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.util.httpAccount.java

public Account getAccountObject(String tel) {
    String telefono = tel.replace("-", "");
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;//w  ww.j  ava 2 s . com
    Account account = new Account();
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            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();
                }
            }

            String jsonResult = sb.toString();
            // System.out.println(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");

            //System.out.println("objeto normal 1 "+dataJson.toString());
            //
            //
            // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
            String jsonString2 = dataJson.toString();
            String temp = dataJson.toString();
            temp = jsonString2.replace("[", "");
            jsonString2 = temp.replace("]", "");
            // System.out.println("new json string"+jsonString2);

            JSONObject objJson2 = new JSONObject(jsonString2);
            // System.out.println("el objeto simple json es " + objJson2.toString());

            // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");
            String account1 = objJson2.optString("account");
            // System.out.println(account1);
            JSONObject objJson3 = new JSONObject(account1);
            //   System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
            //   System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
            String firstName = objJson3.getString("first_name");
            System.out.println(firstName);
            System.out.println(objJson3.get("language_id"));
            //  System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
            Gson gson = new Gson();
            account = gson.fromJson(objJson3.toString(), Account.class);
            //System.out.println(account.getFirst_name());
            // System.out.println(account.getCreation());
            account.setLanguaje_id(objJson3.get("language_id").toString());
            account.setId(objJson3.get("id").toString());
            account.setBalance(objJson3.get("balance").toString());
            System.out.println("el id del account es " + account.getId());

        } else {
            System.out.print("no se pudo conectar con el servidor");
            account = null;
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return account;
}

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

/** {@inheritDoc} */
@Override/*from   w w  w  .j  a  va 2 s.  c om*/
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);
    }//ww w . j a v a  2s .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;// w w  w .  j a  v a2 s .com
    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;
}

From source file:com.soomla.store.domain.VirtualCategory.java

/** Constructor
 *
 * Generates an instance of {@link VirtualCategory} from a JSONObject.
 * @param jsonObject is a JSONObject representation of the wanted {@link VirtualCategory}.
 * @throws JSONException//w  ww  .  j  ava2 s  . com
 */
public VirtualCategory(JSONObject jsonObject) throws JSONException {
    mName = jsonObject.getString(JSONConsts.CATEGORY_NAME);

    JSONArray goodsArr = jsonObject.getJSONArray(JSONConsts.CATEGORY_GOODSITEMIDS);
    for (int i = 0; i < goodsArr.length(); i++) {
        String goodItemId = goodsArr.getString(i);
        mGoodsItemIds.add(goodItemId);
    }
}

From source file:org.dasein.cloud.benchmark.Suite.java

static public void main(String... args) throws Exception {
    ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>();
    ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>();

    for (String suiteFile : args) {
        HashMap<String, Object> suite = new HashMap<String, Object>();

        ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile)));
        StringBuilder json = new StringBuilder();
        String line;//ww  w .  j a v  a 2s . com

        while ((line = reader.readLine()) != null) {
            json.append(line);
            json.append("\n");
        }
        JSONObject ob = new JSONObject(json.toString());

        suite.put("name", ob.getString("name"));
        suite.put("description", ob.getString("description"));

        JSONArray benchmarkClasses = ob.getJSONArray("benchmarks");

        for (int i = 0; i < benchmarkClasses.length(); i++) {
            String cname = benchmarkClasses.getString(i);

            benchmarks.add((Benchmark) Class.forName(cname).newInstance());
        }

        JSONArray clouds = ob.getJSONArray("clouds");

        for (int i = 0; i < clouds.length(); i++) {
            JSONObject cloud = clouds.getJSONObject(i);

            if (cloud.has("regions")) {
                JSONObject regions = cloud.getJSONObject("regions");
                String[] regionIds = JSONObject.getNames(regions);

                if (regionIds != null) {
                    for (String regionId : regionIds) {
                        final JSONObject regionCfg = regions.getJSONObject(regionId);
                        String cname = cloud.getString("providerClass");
                        CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance();
                        JSONObject ctxCfg = cloud.getJSONObject("context");
                        ProviderContext ctx = new ProviderContext();

                        ctx.setEndpoint(regionCfg.getString("endpoint"));
                        ctx.setAccountNumber(ctxCfg.getString("accountNumber"));
                        ctx.setRegionId(regionId);
                        if (ctxCfg.has("accessPublic")) {
                            ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("accessPrivate")) {
                            ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8"));
                        }
                        ctx.setCloudName(ctxCfg.getString("cloudName"));
                        ctx.setProviderName(ctxCfg.getString("providerName"));
                        if (ctxCfg.has("x509Cert")) {
                            ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("x509Key")) {
                            ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("customProperties")) {
                            JSONObject p = ctxCfg.getJSONObject("customProperties");
                            String[] names = JSONObject.getNames(p);

                            if (names != null) {
                                Properties props = new Properties();

                                for (String name : names) {
                                    String value = p.getString(name);

                                    if (value != null) {
                                        props.put(name, value);
                                    }
                                }
                                ctx.setCustomProperties(props);
                            }
                        }
                        provider.connect(ctx);

                        Suite s = new Suite(benchmarks, provider);

                        tests.add(s.runBenchmarks(regionCfg));
                    }
                }
            }
        }
        suite.put("benchmarks", tests);
        suites.add(suite);
    }
    System.out.println((new JSONArray(suites)).toString());
}

From source file:com.asd.littleprincesbeauty.data.Task.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }//from   w w w.  java 2  s  .  com

    try {
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

        if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
            Log.e(TAG, "invalid type");
            return;
        }

        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                setName(data.getString(DataColumns.CONTENT));
                break;
            }
        }

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:com.autburst.picture.server.PictureServer.java

public String[] getImageList(String id) throws Exception {
    HttpRequest request = new HttpRequest();
    String url = BASE_URL + "/" + id;

    Log.d(TAG, "getImageList - url: " + url);

    String response = request.get(url);

    if (response != null && !response.equals("null")) {
        //parse JSON
        JSONObject json = new JSONObject(response);

        JSONArray jsonArray = null;//from  w w w.  j ava 2 s. com
        String singleFileName = null;
        try {
            jsonArray = json.getJSONArray("files");
        } catch (JSONException e) {
            Log.e(TAG, "No JSONArray returned!");

            //get single filename
            singleFileName = json.getString("files");
        }

        if (jsonArray == null) {
            singleFileName = json.getString("files");
            Log.d(TAG, "getImageList - Server returned one file " + singleFileName);
            return new String[] { singleFileName };
        } else {
            String[] resultList = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                resultList[i] = jsonArray.getString(i);
                Log.d(TAG, "getImageList - Server returned " + resultList[i]);
            }
            return resultList;
        }
    } else {
        Log.d(TAG, "getImageList - Server returned null images");
        return new String[0];
    }
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public ArrayList<Student> fetchStudent(Classblock classBlock) {
    ArrayList<Student> items = new ArrayList<Student>();

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");

    try {// ww w  . java2  s  .  com
        String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_GET_STUDENTS)
                .appendQueryParameter("school", schoolName)
                .appendQueryParameter("login", User.getInstance().getLogin())
                .appendQueryParameter("password", User.getInstance().getPassword())
                .appendQueryParameter("idGroup", String.valueOf(classBlock.getIdGroup()))
                .appendQueryParameter("idClassBlock", String.valueOf(classBlock.getId()))
                .appendQueryParameter("date", formatter.format(classBlock.getDate())).build().toString();

        Log.i(TAG, "url: " + url);

        String data = AtmNet.getUrl(url);
        Log.i(TAG, "url: " + data);

        JSONObject jsonObject = new JSONObject(data);
        JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));

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

            Student item = new Student();

            item.setId(row.getInt("id"));
            item.setFullname(row.getString("fullname"));
            item.setName(row.getString("name"));
            item.setSurname1(row.getString("surname1"));
            item.setSurname2(row.getString("surname2"));
            item.setMissType(0);
            item.setNotMaterial(false);
            item.setNetworkTransit(false);

            if (row.has("misses")) {
                JSONArray misses = row.getJSONArray("misses");
                for (int j = 0; j < misses.length(); j++) {
                    int miss = misses.getInt(j);
                    if (miss > NOT_MISS && miss <= EXPULSION) {
                        item.setMissType(miss);
                    }
                    if (miss == NOT_MATERIAL)
                        item.setNotMaterial(true);
                }
            }

            items.add(item);
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }
    return items;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

@Override
public Collection<PointOfInterest> read() {
    final Collection<PointOfInterest> pois;

    try {//from  w  w w .  ja v a  2  s .  co  m
        JSONObject geoJson = new JSONObject(geoJsonString);

        String type = geoJson.getString("type");

        if (type.equals("FeatureCollection")) {
            pois = fromFeatureCollection(geoJson.getJSONArray("features"));
        } else if (type.equals("GeometryCollection")) {
            pois = fromGeometryCollection(geoJson.getJSONArray("geometries"));
        } else {
            throw new IllegalArgumentException("GeoJson of unknown type");
        }
    } catch (JSONException e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    return pois;
}