Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:mr.robotto.engine.loader.components.mesh.MrMeshLoader.java

private void loadKeys(Map<Integer, MrBufferKey> list, JSONArray keys) throws JSONException {
    for (int i = 0; i < keys.length(); i++) {
        JSONObject jsonKey = keys.getJSONObject(i);
        MrBufferKeyLoader loader = new MrBufferKeyLoader(jsonKey);
        MrBufferKey key = loader.parse();
        //list.addAttributeKey(key);
        list.put(key.getAttributeType(), key);
    }//from   w  ww.j  a  va 2 s . co m
}

From source file:com.wglxy.example.dashL.SearchActivity.java

ArrayList<User> parseJSON(String results) throws JSONException, NullPointerException {
    ArrayList<User> list = new ArrayList<User>();
    JSONObject jsonResult = new JSONObject(results);
    int status = jsonResult.getInt("status");
    int numResults = jsonResult.getInt("numResults");

    if (status != 200 && numResults <= 0)
        return list;
    else {/*from  w w  w.  jav a  2 s. c  om*/
        JSONArray arr = jsonResult.getJSONArray("results");
        Log.e(LOG_TAG, "results: " + arr.length());

        for (int i = 0; i < arr.length(); i++) {
            JSONObject jsonObject = arr.getJSONObject(i);
            User user = new User();
            int id = jsonObject.getInt("id");
            String email = jsonObject.getString("email");
            String first_name = jsonObject.getString("first_name");
            String last_name = jsonObject.getString("last_name");
            String business_name = jsonObject.getString("business_name");
            String services = jsonObject.getString("services");
            String address = jsonObject.getString("address");
            int stars = jsonObject.getInt("stars");
            String image = Constants.API_BASE_IMAGE_URL + jsonObject.getString("image");
            Log.e(LOG_TAG, "image: " + image);

            user.setId(id);
            user.setEmail(email);
            user.setFirst_name(first_name);
            user.setLast_name(last_name);
            user.setBusiness_name(business_name);
            user.setAddress(address);
            user.setServices(services);
            user.setStars(stars);
            user.setImage(image);

            list.add(user);
        }
        return list;
    }
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*//*from ww w. j a  v a 2 s .c o  m*/
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

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

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:com.brennasoft.facebookdashclockextension.fbclient.NotificationsRequest.java

private NotificationsResponse parseResponse(Response response) {
    NotificationsResponse notificationsResponse = new NotificationsResponse();
    GraphObject graphObject = response.getGraphObject();
    try {// w  ww  . ja  v a  2s  .  c  om
        JSONArray data = graphObject.getInnerJSONObject().getJSONArray("data");
        notificationsResponse.count = data.length();
        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i);
            notificationsResponse.addNotification(object.getString("notification_id"),
                    object.getLong("updated_time"), object.getString("title_text"));
        }
        notificationsResponse.success = true;
    } catch (JSONException e) {
        Crashlytics.logException(e);
    }
    return notificationsResponse;
}

From source file:org.hydracache.client.partition.PartitionAwareClient.java

@Override
public synchronized List<Identity> listNodes() throws Exception {
    log.info("Retrieving list of nodes.");

    RequestMessage requestMessage = new RequestMessage();
    requestMessage.setMethod(GET);/*from www.  ja  v a2 s  .  c  o  m*/
    requestMessage.setPath("registry");

    // Pick a random node to connect to
    Random rnd = new Random();
    int nextInt = rnd.nextInt(seedServerIds.size());
    Identity identity = seedServerIds.get(nextInt);

    ResponseMessage responseMessage = messager.sendMessage(identity, nodePartition, requestMessage);

    if (responseMessage == null)
        throw new ClientException("Failed to retrieve node registry.");

    List<Identity> identities = new LinkedList<Identity>();

    String registry = new String(responseMessage.getResponseBody());
    log.debug("Received registry: " + registry);
    JSONArray seedServerArray = new JSONArray(registry);
    for (int i = 0; i < seedServerArray.length(); i++) {
        JSONObject seedServer = seedServerArray.getJSONObject(i);

        identities.add(new Identity(InetAddress.getByName(seedServer.getString(IP)), seedServer.getInt(PORT)));
    }
    return identities;
}

From source file:org.everit.json.schema.ObjectComparator.java

private static boolean deepEqualArrays(final JSONArray arr1, final JSONArray arr2) {
    if (arr1.length() != arr2.length()) {
        return false;
    }//w  ww .  j  a v a2s.  c  om
    for (int i = 0; i < arr1.length(); ++i) {
        if (!deepEquals(arr1.get(i), arr2.get(i))) {
            return false;
        }
    }
    return true;
}

From source file:com.tune.reporting.base.endpoints.EndpointBase.java

/**
 * Fetch all fields from model and related models of this endpoint.
 *
 * @return Map All endpoint fields.//  www.ja  v  a 2  s .  c  o m
 *
 * @throws TuneServiceException If service fails to handle post request.
 * @throws TuneSdkException If error within SDK.
 */
protected final Map<String, Map<String, String>> getEndpointFields()
        throws TuneServiceException, TuneSdkException {
    Map<String, String> mapQueryString = new HashMap<String, String>();
    mapQueryString.put("controllers", this.controller);
    mapQueryString.put("details", "modelName,fields");

    TuneServiceClient client = new TuneServiceClient("apidoc", "get_controllers", this.getAuthKey(),
            this.getAuthType(), mapQueryString);

    client.call();

    TuneServiceResponse response = client.getResponse();
    int httpCode = response.getHttpCode();
    JSONArray data = (JSONArray) response.getData();

    if (httpCode != HTTP_STATUS_OK) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(
                String.format("Connection failure '%s': Request: '%s'", httpCode, requestUrl));
    }

    if ((null == data) || (data.length() == 0)) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(String.format("Failed to get fields for endpoint: '%s', Request: '%s'",
                this.controller, requestUrl));
    }

    try {
        JSONObject endpointMetaData = data.getJSONObject(0);

        this.endpointModelName = endpointMetaData.getString("modelName");
        JSONArray endpointFields = endpointMetaData.getJSONArray("fields");

        Map<String, Map<String, String>> fieldsFound = new HashMap<String, Map<String, String>>();
        Map<String, Set<String>> relatedFields = new HashMap<String, Set<String>>();

        for (int i = 0; i < endpointFields.length(); i++) {
            JSONObject endpointField = endpointFields.getJSONObject(i);
            Boolean fieldRelated = endpointField.getBoolean("related");
            String fieldType = endpointField.getString("type");
            String fieldName = endpointField.getString("name");
            Boolean fieldDefault = endpointField.has("fieldDefault") ? endpointField.getBoolean("fieldDefault")
                    : false;

            if (fieldRelated) {
                if (fieldType.equals("property")) {
                    String relatedProperty = fieldName;
                    if (!relatedFields.containsKey(relatedProperty)) {
                        relatedFields.put(relatedProperty, new HashSet<String>());
                    }
                    continue;
                }

                String[] fieldRelatedNameParts = fieldName.split("\\.");
                String relatedProperty = fieldRelatedNameParts[0];
                String relatedFieldName = fieldRelatedNameParts[1];

                if (!relatedFields.containsKey(relatedProperty)) {
                    relatedFields.put(relatedProperty, new HashSet<String>());
                }

                Set<String> relatedFieldFields = relatedFields.get(relatedProperty);
                relatedFieldFields.add(relatedFieldName);
                relatedFields.put(relatedProperty, relatedFieldFields);
                continue;
            }

            Map<String, String> fieldFoundInfo = new HashMap<String, String>();
            fieldFoundInfo.put("default", Boolean.toString(fieldDefault));
            fieldFoundInfo.put("related", "false");
            fieldsFound.put(fieldName, fieldFoundInfo);
        }

        Map<String, Map<String, String>> fieldsFoundMerged = new HashMap<String, Map<String, String>>();
        Iterator<Map.Entry<String, Map<String, String>>> it = fieldsFound.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, Map<String, String>> pairs = it.next();

            String fieldFoundName = pairs.getKey();
            Map<String, String> fieldFoundInfo = pairs.getValue();

            fieldsFoundMerged.put(fieldFoundName, fieldFoundInfo);

            if ((fieldFoundName != "_id") && fieldFoundName.endsWith("_id")) {
                String relatedProperty = fieldFoundName.substring(0, fieldFoundName.length() - 3);
                if (relatedFields.containsKey(relatedProperty)
                        && !relatedFields.get(relatedProperty).isEmpty()) {
                    for (String relatedFieldName : relatedFields.get(relatedProperty)) {
                        if ("id" == relatedFieldName) {
                            continue;
                        }
                        String relatedPropertyFieldName = String.format("%s.%s", relatedProperty,
                                relatedFieldName);
                        Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                        relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                        relatedPropertyFieldInfo.put("related", "true");
                        fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                    }
                } else {
                    Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                    relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                    relatedPropertyFieldInfo.put("related", "true");
                    String relatedPropertyFieldName = String.format("%s.%s", relatedProperty, "name");
                    fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                }
            }
        }

        this.endpointFields = fieldsFoundMerged;

    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    return this.endpointFields;
}

From source file:com.endiansoftware.echo.remotewatch.MainActivity.java

public void callback(String response) {
    StringBuffer sb = new StringBuffer();
    try {//from  w  w  w  .j a  v a  2 s  .  com
        // "kkt_list"   ? JSON ?
        JSONArray Array = new JSONArray(response);
        for (int i = 0; i < Array.length(); i++) {
            // bodylist ?  JSON ? JSON  ? ?
            JSONObject insideObject = Array.getJSONObject(i);

            sb.append(insideObject.getString("m_Key")).append(" : ").append(insideObject.getString("m_Value"))
                    .append("\n");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mDisplay.setText(sb.toString());
}

From source file:com.guipenedo.pokeradar.activities.settings.PokemonFilterSettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getDelegate().installViewFactory();/*from w w  w. j  a  v a 2 s .  c o  m*/
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);
    PreferenceCategory category = new PreferenceCategory(this);
    category.setTitle(R.string.filter_pokemons);
    screen.addPreference(category);
    try {
        JSONArray pokemonList = new JSONArray(Utils.loadJSONFromFile(this, "pokemon.json"));
        for (int i = 0; i < pokemonList.length(); i++) {
            JSONObject pokemon = pokemonList.getJSONObject(i);
            CheckBoxPreference checkBox = new CheckBoxPreference(this);
            checkBox.setTitle(pokemon.getString("Name"));
            checkBox.setIcon(new BitmapDrawable(getResources(),
                    Utils.bitmapForPokemon(this, Integer.parseInt(pokemon.getString("Number")))));
            checkBox.setDefaultValue(true);
            checkBox.setSummary(String.format(getString(R.string.setting_filter_pokemon_summary),
                    pokemon.getString("Name")));
            checkBox.setKey("pref_key_show_pokemon_" + Integer.parseInt(pokemon.getString("Number")));
            category.addPreference(checkBox);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    setPreferenceScreen(screen);
}

From source file:com.trk.aboutme.facebook.Request.java

private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
        boolean passByValue) throws IOException {
    Class<?> valueClass = value.getClass();
    if (GraphObject.class.isAssignableFrom(valueClass)) {
        value = ((GraphObject) value).getInnerJSONObject();
        valueClass = value.getClass();/*  www . j av  a2s.c  o m*/
    } else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
        value = ((GraphObjectList<?>) value).getInnerJSONArray();
        valueClass = value.getClass();
    }

    if (JSONObject.class.isAssignableFrom(valueClass)) {
        JSONObject jsonObject = (JSONObject) value;
        if (passByValue) {
            // We need to pass all properties of this object in key[propertyName] format.
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String propertyName = keys.next();
                String subKey = String.format("%s[%s]", key, propertyName);
                processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
            }
        } else {
            // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
            // for "key"
            if (jsonObject.has("id")) {
                processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
            } else if (jsonObject.has("url")) {
                processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
            }
        }
    } else if (JSONArray.class.isAssignableFrom(valueClass)) {
        JSONArray jsonArray = (JSONArray) value;
        int length = jsonArray.length();
        for (int i = 0; i < length; ++i) {
            String subKey = String.format("%s[%d]", key, i);
            processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
        }
    } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass)
            || Boolean.class.isAssignableFrom(valueClass)) {
        serializer.writeString(key, value.toString());
    } else if (Date.class.isAssignableFrom(valueClass)) {
        Date date = (Date) value;
        // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
        // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
        // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
        // that is what we support here. Apps that need pre-migration behavior can explicitly send these as
        // integer timestamps rather than Dates.
        final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
        serializer.writeString(key, iso8601DateFormat.format(date));
    }
}