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.endiansoftware.echo.remotewatch.MainActivity.java

public void callback(String response) {
    StringBuffer sb = new StringBuffer();
    try {/*from w ww  . j  ava  2s  .co  m*/
        // "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.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *//* w  w w  .  ja v  a2s.c  o  m*/
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }//from  w ww  .j  a  va  2  s.  c  o  m
    // FIXME: until core fixes the annotation for architecture let's assume it's nullable
    String cacheName = "productsALL";
    if (architecture != null) {
        cacheName = "products" + architecture.name();
    }
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName,
            VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
    Iterable<VirtualMachineProduct> products = cache.get(ctx);

    if (products == null) {
        List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();

        try {
            InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");

            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

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

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject productSet = arr.getJSONObject(i);
                    String cloud, providerName;

                    if (productSet.has("cloud")) {
                        cloud = productSet.getString("cloud");
                    } else {
                        continue;
                    }
                    if (productSet.has("provider")) {
                        providerName = productSet.getString("provider");
                    } else {
                        continue;
                    }
                    if (!productSet.has("products")) {
                        continue;
                    }
                    if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) {
                        toCache = productSet;
                    }
                    if (providerName.equalsIgnoreCase(getProvider().getProviderName())
                            && cloud.equalsIgnoreCase(getProvider().getCloudName())) {
                        toCache = productSet;
                        break;
                    }
                }
                if (toCache == null) {
                    logger.warn("No products were defined");
                    return Collections.emptyList();
                }
                JSONArray plist = toCache.getJSONArray("products");

                for (int i = 0; i < plist.length(); i++) {
                    JSONObject product = plist.getJSONObject(i);
                    boolean supported = false;

                    if (architecture != null) {
                        if (product.has("architectures")) {
                            JSONArray architectures = product.getJSONArray("architectures");

                            for (int j = 0; j < architectures.length(); j++) {
                                String a = architectures.getString(j);

                                if (architecture.name().equals(a)) {
                                    supported = true;
                                    break;
                                }
                            }
                        }
                        if (!supported) {
                            continue;
                        }
                    }
                    if (product.has("excludesRegions")) {
                        JSONArray regions = product.getJSONArray("excludesRegions");

                        for (int j = 0; j < regions.length(); j++) {
                            String r = regions.getString(j);

                            if (r.equals(ctx.getRegionId())) {
                                supported = false;
                                break;
                            }
                        }
                    }
                    if (!supported) {
                        continue;
                    }
                    VirtualMachineProduct prd = toProduct(product);

                    if (prd != null) {
                        if (options != null) {
                            if (options.matches(prd)) {
                                list.add(prd);
                            }
                        } else {
                            list.add(prd);
                        }
                    }

                }

            } else {
                logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
            }
            input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
            if (input != null) {
                ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
                TreeSet<String> discard = new TreeSet<String>();
                boolean discardAll = false;

                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

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

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject listing = arr.getJSONObject(i);
                    String cloud, providerName, endpoint = null;

                    if (listing.has("cloud")) {
                        cloud = listing.getString("cloud");
                    } else {
                        continue;
                    }
                    if (listing.has("provider")) {
                        providerName = listing.getString("provider");
                    } else {
                        continue;
                    }
                    if (listing.has("endpoint")) {
                        endpoint = listing.getString("endpoint");
                    }
                    if (!cloud.equals(getProvider().getCloudName())
                            || !providerName.equals(getProvider().getProviderName())) {
                        continue;
                    }
                    if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) {
                        toCache = listing;
                        break;
                    }
                    if (endpoint == null && toCache == null) {
                        toCache = listing;
                    }
                }
                if (toCache != null) {
                    if (toCache.has("discardDefaults")) {
                        discardAll = toCache.getBoolean("discardDefaults");
                    }
                    if (toCache.has("discard")) {
                        JSONArray dlist = toCache.getJSONArray("discard");

                        for (int i = 0; i < dlist.length(); i++) {
                            discard.add(dlist.getString(i));
                        }
                    }
                    if (toCache.has("products")) {
                        JSONArray plist = toCache.getJSONArray("products");

                        for (int i = 0; i < plist.length(); i++) {
                            JSONObject product = plist.getJSONObject(i);
                            boolean supported = false;
                            if (architecture != null) {

                                if (product.has("architectures")) {
                                    JSONArray architectures = product.getJSONArray("architectures");

                                    for (int j = 0; j < architectures.length(); j++) {
                                        String a = architectures.getString(j);

                                        if (architecture.name().equals(a)) {
                                            supported = true;
                                            break;
                                        }
                                    }
                                }
                                if (!supported) {
                                    continue;
                                }
                            }
                            if (product.has("excludesRegions")) {
                                JSONArray regions = product.getJSONArray("excludesRegions");

                                for (int j = 0; j < regions.length(); j++) {
                                    String r = regions.getString(j);

                                    if (r.equals(ctx.getRegionId())) {
                                        supported = false;
                                        break;
                                    }
                                }
                            }
                            if (!supported) {
                                continue;
                            }
                            VirtualMachineProduct prd = toProduct(product);

                            if (prd != null) {
                                customList.add(prd);
                            }
                        }
                    }
                    if (!discardAll) {
                        for (VirtualMachineProduct product : list) {
                            if (!discard.contains(product.getProviderProductId())) {
                                customList.add(product);
                            }
                        }
                    }
                    list = customList;
                }
            }
            products = list;
            cache.put(ctx, products);

        } catch (IOException e) {
            throw new InternalException(e);
        } catch (JSONException e) {
            throw new InternalException(e);
        }
    }
    return products;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*/* w  w  w. j av a2s  .c o m*/
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.liferay.mobile.android.auth.SignIn.java

public static void signIn(final Session session, final JSONObjectCallback callback, final SignInMethod method) {

    GroupService groupService = new GroupService(session);

    session.setCallback(new JSONArrayCallback() {

        @Override// w w  w . j a  v a 2s.c o  m
        public void onSuccess(JSONArray sites) {
            if (sites.length() == 0) {
                onFailure(new Exception("User doesn't belong to any site"));
            }

            try {
                JSONObject site = sites.getJSONObject(0);
                long companyId = site.getLong("companyId");

                Session userSession = new SessionImpl(session);
                userSession.setCallback(callback);

                UserService userService = new UserService(userSession);

                String username = getUsername(session);

                if (method == SignInMethod.EMAIL) {
                    userService.getUserByEmailAddress(companyId, username);
                } else if (method == SignInMethod.USER_ID) {
                    userService.getUserById(Long.parseLong(username));
                } else {
                    userService.getUserByScreenName(companyId, username);
                }
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            callback.onFailure(exception);
        }

    });

    try {
        groupService.getUserSitesGroups();
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:com.footprint.cordova.plugin.localnotification.Restore.java

@Override
public void onReceive(Context context, Intent intent) {
    // The application context needs to be set as first
    LocalNotification.setContext(context);

    // Obtain alarm details form Shared Preferences
    SharedPreferences alarms = LocalNotification.getSharedPreferences();
    Set<String> alarmIds = alarms.getAll().keySet();

    /*/*from   w ww  .  j a  va 2 s  .c  o m*/
     * For each alarm, parse its alarm options and register is again with
     * the Alarm Manager
     */
    for (String alarmId : alarmIds) {
        try {
            JSONArray args = new JSONArray(alarms.getString(alarmId, ""));
            Options options = new Options(context).parse(args.getJSONObject(0));

            /*
             * If the trigger date was in the past, the notification will be displayed immediately.
             */
            LocalNotification.add(options, false);

        } catch (JSONException e) {
        }
    }
}

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void extractEntities(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex,
        final TwitterEntityType entityType) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    String tweetText = JSON_TEXT_PROPERTY.getFrom(jsonTweet);
    // only process if text is found in the tweet
    if (tweetText != null && !tweetText.trim().isEmpty()) {
        String tweetId = tweetVertex.getId().toString();
        User user = getUser();//w ww  .j  av  a2  s .  co m
        Graph graph = getGraph();
        OntologyRepository ontRepo = getOntologyRepository();
        AuditRepository auditRepo = getAuditRepository();

        Concept concept = ontRepo.getConceptByName(entityType.getConceptName());
        Vertex conceptVertex = concept.getVertex();
        String relDispName = conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0)
                .toString();

        JSONArray entities = jsonTweet.getJSONObject("entities").getJSONArray(entityType.getJsonKey());
        List<TermMentionModel> mentions = new ArrayList<TermMentionModel>();

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            String id;
            String sign = entity.getString(entityType.getSignKey());
            if (entityType.getConceptName().equals(CONCEPT_TWITTER_MENTION)) {
                id = TWITTER_USER_PREFIX + entity.get("id");
            } else if (entityType.getConceptName().equals(CONCEPT_TWITTER_HASHTAG)) {
                sign = sign.toLowerCase();
                id = TWITTER_HASHTAG_PREFIX + sign;
            } else {
                try {
                    id = URLEncoder.encode(TWITTER_URL_PREFIX + sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("URL id could not be UTF-8 encoded");
                }
            }
            checkNotNull(sign, "Term sign cannot be null");
            JSONArray indices = entity.getJSONArray("indices");
            TermMentionRowKey termMentionRowKey = new TermMentionRowKey(tweetId, indices.getLong(0),
                    indices.getLong(1));
            TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
            termMention.getMetadata().setSign(sign)
                    .setOntologyClassUri(
                            (String) conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0))
                    .setConceptGraphVertexId(concept.getId()).setVertexId(id);
            mentions.add(termMention);
        }

        for (TermMentionModel mention : mentions) {
            String sign = mention.getMetadata().getSign().toLowerCase();
            String rowKey = mention.getRowKey().toString();
            String id = mention.getMetadata().getGraphVertexId();

            ElementMutation<Vertex> termVertexMutation;
            Vertex termVertex = graph.getVertex(id, user.getAuthorizations());
            if (termVertex == null) {
                termVertexMutation = graph.prepareVertex(id, visibility, user.getAuthorizations());
            } else {
                termVertexMutation = termVertex.prepareMutation();
            }

            TITLE.setProperty(termVertexMutation, sign, visibility);
            ROW_KEY.setProperty(termVertexMutation, rowKey, visibility);
            CONCEPT_TYPE.setProperty(termVertexMutation, concept.getId(), visibility);

            if (!(termVertexMutation instanceof ExistingElementMutation)) {
                termVertex = termVertexMutation.save();
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
            } else {
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
                termVertex = termVertexMutation.save();
            }

            String termId = termVertex.getId().toString();

            mention.getMetadata().setVertexId(termId);
            getTermMentionRepository().save(mention);

            graph.addEdge(tweetVertex, termVertex, entityType.getRelationshipLabel(), visibility,
                    user.getAuthorizations());

            auditRepo.auditRelationship(AuditAction.CREATE, tweetVertex, termVertex, relDispName, processId, "",
                    user, visibility);
            graph.flush();
        }
    }
}

From source file:net.di2e.ddf.argo.probe.responselistener.ProbeResponseEndpoint.java

@POST
@Consumes("application/json")
public void getJSONServices(String jsonResponse) {
    LOGGER.debug("Got a probe response in JSON format:\n{}", jsonResponse);
    JSONArray services = new JSONArray(jsonResponse);
    Set<String> createdSources = new HashSet<String>();
    for (int i = 0; i < services.length(); i++) {
        JSONObject jsonService = services.getJSONObject(i);
        // determine factory pid
        String sourceId = jsonService.getString(ArgoConstants.ID_KEY);
        if (!sourceIdExists(sourceId, createdSources)) {
            String serviceContractId = jsonService.getString(ArgoConstants.SERVICE_CONTRACTID_KEY);
            String serviceType = getServiceType(serviceContractId);
            if (serviceType != null) {
                String pid = serviceResolver.getFactoryPid(serviceType);
                LOGGER.debug(// w  w  w  . j a  v  a2  s .c  om
                        "Got a factory pid of '{}' for service '{}' with service contract id '{}' so attempting to create new source '{}'",
                        pid, serviceType, serviceContractId, sourceId);
                createSource(pid, sourceId, jsonService.getString(ArgoConstants.URL_KEY));
                createdSources.add(sourceId);
            } else {
                LOGGER.debug("Could not find a Service Type for the Service Contract ID '{}'",
                        serviceContractId);
            }
        } else {
            LOGGER.debug(
                    "A Source with id '{}' already exists, so not creating a new one from probe, but checking if any values should be overridden",
                    sourceId);
            // TODO override properties
        }
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussionBoards API operation for Mandatory fields.
 * Expecting Response header '200' and 'post_count' JSONObject in returned
 * JSONArray./*from  w  ww. ja v  a 2  s . com*/
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Boards's getDiscussionBoards operation integration test for Mandatory fields")
public void testGetDiscussionBoardsMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussionBoards_mandatory.txt";
    String methodName = "boards_getBoard";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString,
            meetupConnectorProperties.getProperty("access_token"));
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);

        JSONArray jsonArray = ConnectorIntegrationUtil.sendRequestJSONArray(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Assert.assertTrue(jsonObject.has("post_count"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}