Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java

/**
 * Mandatory parameter test case for getSeveralArtists method.
 *///w w  w  .j av a2  s. c  o  m
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "spotify {getSeveralArtists} integration test with mandatory parameter.")
public void testGetSeveralArtistsWithMandatoryParameter() throws Exception {
    String jsonRequestFilePath = pathToRequestsDirectory + "getSeveralArtists_Mandatory.txt";
    String methodName = "spotify";
    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));
    String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("artistId1")
            + "," + spotifyConnectorProperties.getProperty("artistId2"));
    try {
        JSONObject jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = new JSONObject(modifiedJsonString);
        String[] ids = jsonObject.getString("artistIds").split(",");
        JSONArray artists = jsonResponse.getJSONArray("artists");
        boolean exi = false;
        for (int i = 0; i < artists.length(); i++) {
            JSONObject a = (JSONObject) artists.get(i);
            if (a.getString("id").equals(ids[0]) || a.getString("id").equals(ids[1])) {
                exi = true;
            }
        }
        Assert.assertEquals(exi, true);
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java

/**
 * Mandatory parameter test case for getTopTracksOfAnArtist method.
 *///  ww  w . ja va 2 s . com
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "spotify {getTopTracksOfAnArtist} integration test with mandatory parameters.")
public void testGetTopTracksOfAnArtistWithMandatoryParameters() throws Exception {
    String jsonRequestFilePath = pathToRequestsDirectory + "getTopTracksOfAnArtist_Mandatory.txt";
    String methodName = "spotify";
    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));
    String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("artistId1"));
    try {
        JSONObject jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = new JSONObject(modifiedJsonString);
        JSONArray artists = ((JSONObject) jsonResponse.getJSONArray("tracks").get(0)).getJSONArray("artists");
        boolean exi = false;
        for (int i = 0; i < artists.length(); i++) {
            JSONObject a = (JSONObject) artists.get(i);
            if (a.getString("id").equals(jsonObject.getString("artistId"))) {
                exi = true;
            }
        }
        Assert.assertEquals(exi, true);
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java

/**
 * Mandatory parameter test case for getSeveralTracks method.
 *///  w  ww  . j  a  v a 2  s .c om
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "spotify {getSeveralTracks} integration test with mandatory parameters.")
public void testGetSeveralTracksWithMandatoryParameters() throws Exception {
    String jsonRequestFilePath = pathToRequestsDirectory + "getSeveralTracks_Mandatory.txt";
    String methodName = "spotify";
    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));
    String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("trackId1")
            + "," + spotifyConnectorProperties.getProperty("trackId2"));
    try {
        JSONObject jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = new JSONObject(modifiedJsonString);
        String[] ids = jsonObject.getString("trackIds").split(",");
        JSONArray tracks = jsonResponse.getJSONArray("tracks");
        boolean exi = false;
        for (int i = 0; i < tracks.length(); i++) {
            JSONObject t = (JSONObject) tracks.get(i);
            if (t.getString("id").equals(ids[0]) || t.getString("id").equals(ids[1])) {
                exi = true;
            }
        }
        Assert.assertEquals(exi, true);
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:menusearch.json.JSONProcessor.java

/**
    */*from w w w  .  j a  va 2s  .  c o  m*/
    * @param JSON string: requires the JSON string of the parameters the user enter for the search
    * @return RecipeSummaryList: a RecipeSummaryList where it contains information about the recipes that matches the search the user made
    * @throws java.io.IOException
    */
public static RecipeSummaryList parseRecipeMatches(String results) throws IOException {
    CourseList courseList = new CourseList();
    RecipeSummaryList list = new RecipeSummaryList();
    JSONTokener tokenizer = new JSONTokener(results);
    JSONObject resultList = new JSONObject(tokenizer);
    JSONArray matches = resultList.getJSONArray("matches");
    for (int i = 0; i < matches.length(); i++) {
        RecipeSummary r = new RecipeSummary();
        JSONObject currentRecipe = matches.getJSONObject(i);
        JSONObject imageUrls = currentRecipe.getJSONObject("imageUrlsBySize");
        String link = "90";
        String number = imageUrls.getString(link);
        r.setImageUrlsBySize(number);

        String source = (String) currentRecipe.getString("sourceDisplayName");
        r.setSourceDisplayName(source);

        JSONArray listOfIngredients = currentRecipe.getJSONArray("ingredients");
        for (int n = 0; n < listOfIngredients.length(); n++) {
            String currentIngredients = listOfIngredients.getString(n);
            r.ingredients.add(currentIngredients);
        }

        String id = (String) currentRecipe.getString("id");
        r.setId(id);

        String recipe = (String) currentRecipe.get("recipeName");
        r.setRecipeName(recipe);

        JSONArray smallImage = currentRecipe.getJSONArray("smallImageUrls");
        for (int l = 0; l < smallImage.length(); l++) {
            String currentUrl = (String) smallImage.get(l);
            r.setSmallImageUrls(currentUrl);
        }
        int timeInSeconds = (int) currentRecipe.getInt("totalTimeInSeconds");
        r.setTotalTimeInSeconds(timeInSeconds);

        String a = "attributes";
        String c = "course";
        if (currentRecipe.has(a)) {
            JSONObject currentAttributes = currentRecipe.getJSONObject(a);
            if (currentAttributes.has(c)) {
                for (int j = 0; j < currentAttributes.getJSONArray(c).length(); j++) {
                    String course = currentAttributes.getJSONArray(c).getString(j);
                    courseList.add(course);
                }
                r.setCourses(courseList);
            }
        }

        CuisineList cuisineList = new CuisineList();

        if (currentRecipe.has(a)) {
            JSONObject currentAttributes = currentRecipe.getJSONObject(a);
            if (currentAttributes.has("cuisine")) {
                for (int j = 0; j < currentAttributes.getJSONArray("cuisine").length(); j++) {
                    String currentCuisine = currentAttributes.getJSONArray("cuisine").getString(j);
                    cuisineList.add(currentCuisine);
                }
                r.setCusines(cuisineList);
            }
        }

        String f = "flavors";
        JSONObject currentFlavors;
        if (currentRecipe.has(f) == true) {

            if (currentRecipe.isNull(f) == false) {
                currentFlavors = currentRecipe.getJSONObject(f);
                double saltyRating = currentFlavors.getDouble("salty");
                double sourRating = currentFlavors.getDouble("sour");
                double sweetRating = currentFlavors.getDouble("sweet");
                double bitterRating = currentFlavors.getDouble("bitter");
                double meatyRating = currentFlavors.getDouble("meaty");
                double piguantRating = currentFlavors.getDouble("piquant");
                r.flavors.setSalty(saltyRating);
                r.flavors.setSour(sourRating);
                r.flavors.setSweet(sweetRating);
                r.flavors.setBitter(bitterRating);
                r.flavors.setMeaty(meatyRating);
                r.flavors.setPiquant(piguantRating);
            }
            if (currentRecipe.get(f) == null) {
                r.flavors = null;
            }
            if (currentRecipe.get(f) == null)
                r.flavors = null;
        }

        double rate = currentRecipe.getInt("rating");
        r.setRating(rate);

        list.matches.add(i, r);

    }

    return list;

}

From source file:curt.android.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException, InterruptedException {

    String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from  w  w w.  j  a va  2 s  .c o m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>();
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.MainActivity.java

void loadRPCMovies() {
    JSONArray arr;
    List<String> ls = new ArrayList<>();
    try {/*from w w w  .ja  v a  2 s  . co m*/
        //Call async method to retrieve the movie list names and check in the movie list
        MethodInformation mi = new MethodInformation("http://10.0.2.2:8080/", "getTitles", new String[] {});
        JSONObject ac = new AsyncCollectionConnect().execute(mi).get();
        arr = (JSONArray) ac.get("result");

        for (int i = 0; i < arr.length(); i++) {
            System.out.println("Loading Movie title " + arr.get(i) + " from RPC");
            addMoviesNotInListFromRPC((String) arr.get(i));
        }
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }
}

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleListSerializer.java

@SuppressWarnings("unchecked")
@Override/* www.  j a va  2 s.co m*/
public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    List list = null;
    try {
        try {
            try {
                if (clazz.isInterface()) {
                    list = new java.util.ArrayList();
                } else
                    list = (List) clazz.newInstance();
            } catch (ClassCastException cce) {
                throw new UnmarshallException("invalid unmarshalling Class " + cce.getMessage());
            }
        } catch (IllegalAccessException iae) {
            throw new UnmarshallException("no access unmarshalling object " + iae.getMessage());
        }
    } catch (InstantiationException ie) {
        throw new UnmarshallException("unable to instantiate unmarshalling object " + ie.getMessage());
    }
    JSONArray jsa = (JSONArray) o;

    state.setSerialized(o, list);
    int i = 0;
    try {
        for (; i < jsa.length(); i++) {
            list.add(ser.unmarshall(state, null, jsa.get(i)));
        }
    } catch (UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage());
    } catch (JSONException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage());
    }
    return list;
}

From source file:org.spiffyui.mvsb.samples.server.CrayonColorsServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONArray fullColorArray;
    String query = request.getParameter("q");

    try {//from www  .  j a v a  2 s  .  c  o  m
        int count = 0;
        if (query.equals(m_lastQuery)) {
            fullColorArray = m_lastResults;
            count = m_lastResults.length();
        } else {
            m_lastQuery = query;

            fullColorArray = new JSONArray();
            for (String[] colorCode : COLOR_CODES) {
                String colorName = colorCode[0];
                String lowerColor = colorName.toLowerCase();
                int has = lowerColor.indexOf(query.toLowerCase());

                if (!query.isEmpty() && (query.equals("*") || has >= 0)) {
                    JSONObject color = new JSONObject();
                    color.put("DisplayName", colorName);
                    color.put("Value", colorCode[1]);
                    color.put("Description", colorCode[2]);
                    color.put("RGB", colorCode[3]);
                    fullColorArray.put(color);
                    count++;
                }
            }
            m_lastResults = fullColorArray;
        }

        //get the partial array to be returned
        int indexFrom = 0;
        if (request.getParameter("indexFrom") != null) {
            indexFrom = Integer.parseInt(request.getParameter("indexFrom"));
        }

        int indexTo = fullColorArray.length() - 1;
        if (request.getParameter("indexTo") != null) {
            indexTo = Integer.parseInt(request.getParameter("indexTo"));
        }

        JSONArray partial = new JSONArray();
        if (fullColorArray.length() > 0) {
            int end = count - 1 > indexTo ? indexTo : count - 1;
            for (int i = indexFrom; i <= end; i++) {
                partial.put(fullColorArray.get(i));
            }
        }
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        JSONObject obj = new JSONObject();
        obj.put("TotalSize", count);
        obj.put("Options", partial);
        out.println(obj.toString());
    } catch (JSONException e) {
        /*
         This should never happen
         */
        LOGGER.throwing(getClass().getName(), "doGet", e);
    }
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

private void processJSONArray(String key, JSONArray jsonArray, Element arrayElement, Namespace namespace,
        List<Namespace> namespaces) throws JSONException {
    String childTypeName = getListElementMap().get(key);

    for (int i = 0; i < jsonArray.length(); i++) {
        if (jsonArray.isNull(i)) {
            continue;
        }//from ww w  .  j a v  a 2s  .  c  o  m

        Element child;
        if (childTypeName == null) {
            child = arrayElement;
        } else {
            child = new Element(childTypeName, namespace);
            arrayElement.addContent(child);
        }

        Object value = jsonArray.get(i);
        processObject(childTypeName, value, child, namespace, namespaces);
    }
}

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementCondition(JSONObject obj, Formula theCondition, MVocab vocab)
        throws JSONException, MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // Condition block is a conjunctive list of conditions. all must apply.
    // Each condition is a conjunctive list of value sets. 
    // Each value set is a disjunctive list of values
    // Keys in the condition block are functions to apply
    // Keys in a condition are attribute names. Values are values.

    // Condition block
    //    Function : {}
    //    Function : {}
    // .../*from w  w  w .j  ava  2 s  . c om*/

    JSONArray conditionNames = obj.names();
    for (int iCondition = 0; iCondition < conditionNames.length(); iCondition++) {
        String cFunction = (String) conditionNames.get(iCondition);
        JSONObject condition = (JSONObject) obj.get(cFunction);
        //MEnvironment.errorStream.println(cFunction + ": "+condition);

        // condition is a key:value pair or multiple such pairs. The value may be an array.
        // Each sub-condition must be met.
        HashSet<Formula> thisCondition = new HashSet<Formula>();

        JSONArray subConditionNames = condition.names();
        for (int iSubCondition = 0; iSubCondition < subConditionNames.length(); iSubCondition++) {
            String cSubKey = (String) subConditionNames.get(iSubCondition);
            Object subcondition = condition.get(cSubKey);

            // Subcondition: is it an array or a single value?
            if (subcondition instanceof JSONArray) {
                JSONArray subarr = (JSONArray) subcondition;
                HashSet<Formula> valuedisj = new HashSet<Formula>();
                for (int iValue = 0; iValue < subarr.length(); iValue++) {
                    //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subarr.get(iValue)+")");
                    Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                            cFunction + "<" + cSubKey + "><" + subarr.get(iValue) + ">");
                    valuedisj.add(theatom);
                }

                thisCondition.add(MFormulaManager.makeDisjunction(valuedisj));
            } else {
                //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subcondition+")");   
                Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                        cFunction + "<" + cSubKey + "><" + subcondition + ">");
                thisCondition.add(theatom);
            }

        }

        theCondition = MFormulaManager.makeAnd(theCondition, MFormulaManager.makeConjunction(thisCondition));
    }

    return theCondition;
}