Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:menusearch.json.JSONProcessor.java

/**
 * /*  w  ww  .  jav a  2 s  .  co  m*/
 * @param results: requires the JSON string of the parameters the user enter for the search
 * @return a RecipeSummaryList where it contains information about the recipes that matches the search the user made
 * @throws IOException
 * @throws JSONException 
 */

public static RecipeSummaryList parseRecipes(String results) throws IOException, JSONException {

    RecipeSummaryList recipeSummary = new RecipeSummaryList();

    JSONObject newObject = new JSONObject(results);
    JSONObject at = newObject.getJSONObject("attribution");

    String html = (String) at.get("html");
    recipeSummary.setHtml(html);

    String url = (String) at.get("url");
    recipeSummary.setUrl(url);

    String text = (String) at.get("text");
    recipeSummary.setText(text);

    String logo = (String) at.get("logo");
    recipeSummary.setLogo(logo);

    int totalMatches = newObject.getInt("totalMatchCount");
    recipeSummary.setTotalmatches(totalMatches);

    return recipeSummary;

}

From source file:menusearch.json.JSONProcessor.java

/**
    */*from w w  w  .j ava2  s .  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:me.mast3rplan.phantombot.cache.UsernameCache.java

public String resolve(String username, Map<String, String> tags) {
    String lusername = username.toLowerCase();

    if (cache.containsKey(lusername)) {
        return cache.get(lusername);
    } else {//from   w  ww.  j  av a 2  s .  c om
        if (tags.containsKey("display-name") && tags.get("display-name").equalsIgnoreCase(lusername)) {
            cache.put(lusername, tags.get("display-name"));

            if (PhantomBot.enableDebugging) {
                com.gmt2001.Console.out
                        .println(">>UsernameCache detected using v3: " + tags.get("display-name"));
            }

            return tags.get("display-name");
        }

        if (username.equalsIgnoreCase("jtv") || username.equalsIgnoreCase("twitchnotify")
                || new Date().before(timeoutExpire)) {
            return username;
        }

        try {
            JSONObject user = TwitchAPIv3.instance().GetUser(lusername);

            if (user.getBoolean("_success")) {
                if (user.getInt("_http") == 200) {
                    String displayName = user.getString("display_name");
                    cache.put(lusername, displayName);

                    return displayName;
                } else {
                    try {
                        throw new Exception("[HTTPErrorException] HTTP " + user.getInt("status") + " "
                                + user.getString("error") + ". req=" + user.getString("_type") + " "
                                + user.getString("_url") + " " + user.getString("_post") + "   "
                                + (user.has("message") && !user.isNull("message")
                                        ? "message=" + user.getString("message")
                                        : "content=" + user.getString("_content")));
                    } catch (Exception e) {
                        com.gmt2001.Console.out.println(
                                "UsernameCache.updateCache>>Failed to get username: " + e.getMessage());
                        com.gmt2001.Console.err.logStackTrace(e);

                        return username;
                    }
                }
            } else {
                if (user.getString("_exception").equalsIgnoreCase("SocketTimeoutException")
                        || user.getString("_exception").equalsIgnoreCase("IOException")) {
                    Calendar c = Calendar.getInstance();

                    if (lastFail.after(new Date())) {
                        numfail++;
                    } else {
                        numfail = 1;
                    }

                    c.add(Calendar.MINUTE, 1);

                    lastFail = c.getTime();

                    if (numfail >= 5) {
                        timeoutExpire = c.getTime();
                    }
                }

                return username;
            }
        } catch (Exception e) {
            com.gmt2001.Console.err.printStackTrace(e);
            return username;
        }
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.SyncDecisionsPacket.java

public SyncDecisionsPacket(JSONObject json) throws JSONException {
    super(json);//ww w  . ja v a2s  . c o m
    this.nodeID = json.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    this.maxDecisionSlot = json.getInt(PaxosPacket.Keys.MAX_S.toString());
    if (json.has(PaxosPacket.Keys.MISS.toString()))
        missingSlotNumbers = Util
                .JSONArrayToArrayListInteger(json.getJSONArray(PaxosPacket.Keys.MISS.toString()));
    else
        missingSlotNumbers = null;
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.SYNC_DECISIONS_REQUEST
            || PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.CHECKPOINT_REQUEST);
    this.packetType = PaxosPacketType.SYNC_DECISIONS_REQUEST;
}

From source file:com.llc.bumpr.sdk.models.Driver.java

/**
 * Constructor to create Driver from JSON
 * @param json The json representation of the driver 
 * @throws JSONException exception thrown from invalid json representation
 *///  w  w  w . java2  s .com
public Driver(JSONObject json) throws JSONException {
    id = json.getInt("id");
    fee = json.getDouble("fee");
    String sRating = json.getString("rating");
    if (sRating.equals("null"))
        rating = 0;
    else
        rating = Double.parseDouble(sRating);
    try {
        position = new Location(json.getDouble("lat"), json.getDouble("lon"));
    } catch (JSONException e) {
        Log.i("com.llc.bumpr.sdk", "Lat/Long not passed to driver");
    }
}

From source file:fr.bde_eseo.eseomega.lacommande.model.LacmdMenu.java

public LacmdMenu(JSONObject obj) throws JSONException {
    super(obj.getString("name"), obj.getString("idstr"), 0, 1, obj.getDouble("price"), ID_CAT_MENU); // no ingredients, but elements yes
    // expressions
    mainElemStr = obj.getString("mainElemStr");
    maxMainElem = obj.getInt("nbMainElem");
    maxSecoElem = obj.getInt("nbSecoElem");
}

From source file:org.droidparts.test.testcase.serialize.JSONTestCase.java

public void testPrimitives() throws Exception {
    JSONSerializer<Primitives> serializer = makeSerializer(Primitives.class);
    Primitives primitives = serializer.deserialize(getPrimitives());
    assertNotNull(primitives.strArr);/*from  w w w . ja va  2s . c om*/
    assertEquals(9000, (long) primitives.longList.get(0));
    //
    JSONObject obj = serializer.serialize(primitives);
    //
    assertEquals(1, obj.getInt("int1"));
    assertEquals(2, obj.getInt("int2"));
    assertEquals(0.5, obj.getDouble("float1"));
    assertEquals(2.5, obj.getDouble("float2"));
    assertEquals(true, obj.getBoolean("boolean1"));
    assertEquals(true, obj.getBoolean("boolean2"));
    assertEquals(true, obj.getBoolean("boolean3"));
    assertEquals(false, obj.getBoolean("boolean4"));
    assertEquals("str", obj.getString("string1"));
    assertEquals(2, obj.getJSONArray("string_array").length());
    assertEquals("two", obj.getJSONArray("string_array").getString(1));
}

From source file:com.github.koraktor.steamcondenser.community.GameItemSchema.java

/**
 * Updates the item definitions of this schema using the Steam Web API
 *
 * @throws WebApiException if the item schema cannot be fetched
 */// w  w w  .j  ava2 s.  c  o  m
public void fetch() throws WebApiException {
    try {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("language", this.language);
        JSONObject data = WebApi.getJSONData("IEconItems_" + this.appId, "GetSchema", 1, params);

        this.attributes = new HashMap<Object, JSONObject>();
        JSONArray attributesData = data.getJSONArray("attributes");
        for (int i = 0; i < attributesData.length(); i++) {
            JSONObject attribute = attributesData.getJSONObject(i);
            this.attributes.put(attribute.getInt("defindex"), attribute);
            this.attributes.put(attribute.getString("name"), attribute);
        }

        this.effects = new HashMap<Integer, JSONObject>();
        JSONArray effectsData = data.getJSONArray("attribute_controlled_attached_particles");
        for (int i = 0; i < effectsData.length(); i++) {
            JSONObject effect = effectsData.getJSONObject(i);
            this.effects.put(effect.getInt("id"), effect);
        }

        this.items = new HashMap<Integer, JSONObject>();
        this.itemNames = new HashMap<String, Integer>();
        JSONArray itemsData = data.getJSONArray("items");
        for (int i = 0; i < itemsData.length(); i++) {
            JSONObject item = itemsData.getJSONObject(i);
            this.items.put(item.getInt("defindex"), item);
            this.itemNames.put(item.getString("name"), item.getInt("defindex"));
        }

        if (data.has("levels")) {
            this.itemLevels = new HashMap<String, Object>();
            JSONArray itemsLevelsData = data.getJSONArray("item_levels");
            for (int i = 0; i < itemsLevelsData.length(); i++) {
                JSONObject itemLevelType = itemsLevelsData.getJSONObject(i);
                HashMap<Integer, String> itemLevels = new HashMap<Integer, String>();
                this.itemLevels.put(itemLevelType.getString("name"), itemLevels);
                for (int j = 0; j < itemLevelType.getJSONArray("levels").length(); j++) {
                    JSONObject itemLevel = itemLevelType.getJSONArray("levels").getJSONObject(j);
                    itemLevels.put(itemLevel.getInt("level"), itemLevel.getString("name"));
                }
            }
        }

        this.itemSets = new HashMap<String, JSONObject>();
        JSONArray itemSetsData = data.getJSONArray("item_sets");
        for (int i = 0; i < itemSetsData.length(); i++) {
            JSONObject itemSet = itemSetsData.getJSONObject(i);
            this.itemSets.put(itemSet.getString("item_set"), itemSet);
        }

        this.origins = new HashMap<Integer, String>();
        JSONArray originsData = data.getJSONArray("originNames");
        for (int i = 0; i < originsData.length(); i++) {
            JSONObject origin = originsData.getJSONObject(i);
            this.origins.put(origin.getInt("origin"), origin.getString("name"));
        }

        this.qualities = new HashMap<Integer, String>();
        JSONObject qualitiesData = data.getJSONObject("qualities");
        Iterator qualityKeys = qualitiesData.keys();
        int index = -1;
        while (qualityKeys.hasNext()) {
            String key = (String) qualityKeys.next();
            index++;
            String qualityName = data.getJSONObject("qualityNames").optString(key, WordUtils.capitalize(key));
            this.qualities.put(index, qualityName);
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }

    this.cache();

    this.fetchDate = new Date();
}

From source file:it.iziozi.iziozi.gui.IORemoteImageSearchActivity.java

private void searchImages(String queryString) {

    mRingProgressDialog = ProgressDialog.show(this, getString(R.string.please_wait),
            getString(R.string.search_in_progress), true);

    mPictograms = new ArrayList<IOPictogram>();

    SharedPreferences prefs = getSharedPreferences(IOApplication.APPLICATION_NAME, Context.MODE_PRIVATE);

    prefs.getString(IOApplication.APPLICATION_LOCALE, Locale.getDefault().getLanguage());

    RequestParams params = new RequestParams();

    params.put("q", queryString);
    params.put("lang", Locale.getDefault().getLanguage());

    IOApiClient.get("pictures", params, new JsonHttpResponseHandler() {

        @Override//from  w ww .  ja  va  2 s  . c  o m
        public void onStart() {
            super.onStart();
            Log.d("http debug", getRequestURI().toString());
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            //something went wrong

            Toast.makeText(getApplicationContext(), getString(R.string.unexpected_response), Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onFinish() {
            super.onFinish();

            mRingProgressDialog.cancel();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
            super.onSuccess(statusCode, headers, response);

            //Correct response

            int iter = response.length();

            if (iter == 0) {

                mEmptyTextView.setVisibility(View.VISIBLE);

            } else {
                for (int i = 0; i < iter; i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        IOPictogram pictogram = new IOPictogram();

                        pictogram.setId(jsonObject.getInt("id"));
                        pictogram.setFilePath(jsonObject.getString("file"));
                        pictogram.setUrl(jsonObject.getString("deepurl"));
                        String text = jsonObject.getString("text");
                        pictogram.setDescription(
                                text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase());
                        //TODO: add type or category

                        mPictograms.add(pictogram);

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

                    RemoteImagesGridAdapter gridAdapter = (RemoteImagesGridAdapter) mGridView.getAdapter();
                    gridAdapter.notifyDataSetChanged();
                    gridAdapter.notifyDataSetInvalidated();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);

            //Timeout, 500, no connection

            Toast.makeText(getApplicationContext(), getString(R.string.request_error), Toast.LENGTH_SHORT)
                    .show();
        }
    });

}

From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java

private void getAllFriends(String urlString, final ArrayList<SocialPerson> socialPersons,
        final ArrayList<String> ids, String token) throws Exception {
    URL url = new URL(urlString);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    checkConnectionErrors(connection);//www .  j a v a2  s . c  om
    InputStream inputStream = connection.getInputStream();
    String response = streamToString(inputStream);
    JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue();

    int jsonStart = 0, jsonCount = 0, jsonTotal = 0;
    String nextToken = null;
    if (jsonObject.has("_start")) {
        jsonStart = jsonObject.getInt("_start");
    }
    if (jsonObject.has("_count")) {
        jsonCount = jsonObject.getInt("_count");
    }
    if (jsonObject.has("_total")) {
        jsonTotal = jsonObject.getInt("_total");
    }
    int start = jsonStart + jsonCount;
    if (jsonTotal > 0 && start > 0 && jsonCount > 0 && jsonTotal > start) {
        nextToken = LINKEDIN_V1_API + "/people/~/connections" + RequestGetFriendsAsyncTask.fields
                + "?oauth2_access_token=" + token + FORMAT_JSON + "&start=" + start + "&count="
                + RequestGetFriendsAsyncTask.count;
    }
    JSONArray jsonResponse = jsonObject.getJSONArray("values");
    int length = jsonResponse.length();
    for (int i = 0; i < length; i++) {
        SocialPerson socialPerson = new SocialPerson();
        getSocialPerson(socialPerson, jsonResponse.getJSONObject(i));
        socialPersons.add(socialPerson);
        ids.add(jsonResponse.getJSONObject(i).getString("id"));
    }

    if ((nextToken != null) && (!TextUtils.isEmpty(nextToken))) {
        getAllFriends(nextToken, socialPersons, ids, token);
    }
}