Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateAmortizationSpinner(ResponseBody result) {

    final List<AmortizationType> amortizationType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> amortizationTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {/*from   www .j  a  v  a 2s  .co m*/
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("amortizationTypeOptions")) {
            JSONArray amortizationTypes = obj.getJSONArray("amortizationTypeOptions");
            for (int i = 0; i < amortizationTypes.length(); i++) {
                JSONObject amortizationTypeObject = amortizationTypes.getJSONObject(i);
                AmortizationType amortization = new AmortizationType();
                amortization.setId(amortizationTypeObject.optInt("id"));
                amortization.setValue(amortizationTypeObject.optString("value"));
                amortizationType.add(amortization);
                amortizationTypeNames.add(amortizationTypeObject.optString("value"));
                amortizationTypeIdHashMap.put(amortization.getValue(), amortization.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> amortizationTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, amortizationTypeNames);
    amortizationTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_amortization.setAdapter(amortizationTypeAdapter);
    sp_amortization.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            amortizationTypeId = amortizationTypeIdHashMap.get(amortizationTypeNames.get(i));
            Log.d("ammortization" + amortizationTypeNames.get(i), String.valueOf(amortizationTypeId));
            if (amortizationTypeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateInterestCalculationPeriodSpinner(ResponseBody result) {

    final List<InterestCalculationPeriodType> interestCalculationPeriodType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> interestCalculationPeriodTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {// w w w  .  ja v  a  2  s  .  c om
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("interestCalculationPeriodTypeOptions")) {
            JSONArray interestCalculationPeriodTypes = obj.getJSONArray("interestCalculationPeriodTypeOptions");
            for (int i = 0; i < interestCalculationPeriodTypes.length(); i++) {
                JSONObject interestCalculationPeriodTypeObject = interestCalculationPeriodTypes
                        .getJSONObject(i);
                InterestCalculationPeriodType interestCalculationPeriod = new InterestCalculationPeriodType();
                interestCalculationPeriod.setId(interestCalculationPeriodTypeObject.optInt("id"));
                interestCalculationPeriod.setValue(interestCalculationPeriodTypeObject.optString("value"));
                interestCalculationPeriodType.add(interestCalculationPeriod);
                interestCalculationPeriodTypeNames.add(interestCalculationPeriodTypeObject.optString("value"));
                interestCalculationPeriodTypeIdHashMap.put(interestCalculationPeriod.getValue(),
                        interestCalculationPeriod.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> interestCalculationPeriodTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, interestCalculationPeriodTypeNames);

    interestCalculationPeriodTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_interestcalculationperiod.setAdapter(interestCalculationPeriodTypeAdapter);
    sp_interestcalculationperiod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            interestCalculationPeriodTypeId = interestCalculationPeriodTypeIdHashMap
                    .get(interestCalculationPeriodTypeNames.get(i));
            Log.d("interestCalculation " + interestCalculationPeriodTypeNames.get(i),
                    String.valueOf(interestCalculationPeriodTypeId));
            if (interestCalculationPeriodTypeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_interestCalculationPeriod),
                        Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflatetransactionProcessingStrategySpinner(ResponseBody result) {

    final List<TransactionProcessingStrategy> transactionProcessingStrategyType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> transactionProcessingStrategyTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {//from  w  ww .j a v a  2 s .c  om
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("transactionProcessingStrategyOptions")) {
            JSONArray transactionProcessingStrategyTypes = obj
                    .getJSONArray("transactionProcessingStrategyOptions");
            for (int i = 0; i < transactionProcessingStrategyTypes.length(); i++) {
                JSONObject transactionProcessingStrategyTypeObject = transactionProcessingStrategyTypes
                        .getJSONObject(i);
                TransactionProcessingStrategy transactionProcessingStrategy = new TransactionProcessingStrategy();
                transactionProcessingStrategy.setId(transactionProcessingStrategyTypeObject.optInt("id"));
                transactionProcessingStrategy
                        .setName(transactionProcessingStrategyTypeObject.optString("name"));
                transactionProcessingStrategyType.add(transactionProcessingStrategy);
                transactionProcessingStrategyTypeNames
                        .add(transactionProcessingStrategyTypeObject.optString("name"));
                transactionProcessingStrategyTypeIdHashMap.put(transactionProcessingStrategy.getName(),
                        transactionProcessingStrategy.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> transactionProcessingStrategyAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, transactionProcessingStrategyTypeNames);

    transactionProcessingStrategyAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);

    sp_repaymentstrategy.setAdapter(transactionProcessingStrategyAdapter);
    sp_repaymentstrategy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            transactionProcessingStrategyId = transactionProcessingStrategyTypeIdHashMap
                    .get(transactionProcessingStrategyTypeNames.get(i));
            Log.d("transactionProcessing " + transactionProcessingStrategyTypeNames.get(i),
                    String.valueOf(transactionProcessingStrategyId));
            if (transactionProcessingStrategyId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_transactionProcessingStrategy),
                        Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateFrequencyPeriodSpinner(ResponseBody result) {

    final List<TermFrequencyTypeOptions> termFrequencyType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> termFrequencyTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {//w w w.ja  v a2  s .c  o m
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("termFrequencyTypeOptions")) {
            JSONArray termFrequencyTypes = obj.getJSONArray("termFrequencyTypeOptions");
            for (int i = 0; i < termFrequencyTypes.length(); i++) {
                JSONObject termFrequencyTypeObject = termFrequencyTypes.getJSONObject(i);
                TermFrequencyTypeOptions termFrequency = new TermFrequencyTypeOptions();
                termFrequency.setId(termFrequencyTypeObject.optInt("id"));
                termFrequency.setValue(termFrequencyTypeObject.optString("value"));
                termFrequencyType.add(termFrequency);
                termFrequencyTypeNames.add(termFrequencyTypeObject.optString("value"));
                termFrequencyTypeIdHashMap.put(termFrequency.getValue(), termFrequency.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> termFrequencyTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, termFrequencyTypeNames);
    termFrequencyTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_payment_periods.setAdapter(termFrequencyTypeAdapter);
    sp_payment_periods.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            loanTermFrequency = termFrequencyTypeIdHashMap.get(termFrequencyTypeNames.get(i));
            Log.d("termFrequencyTypeId" + termFrequencyTypeNames.get(i), String.valueOf(loanTermFrequency));
            if (loanTermFrequency != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

@Override
public void showLoanPurposeSpinner(ResponseBody result) {

    mResponse = result;//from www.  ja v a  2  s . c om

    inflateFrequencyPeriodSpinner(mResponse);
    inflateAmortizationSpinner(mResponse);
    inflateInterestCalculationPeriodSpinner(mResponse);
    //inflaterepaymentFrequencyTypeOptionsSpinner();
    inflatetransactionProcessingStrategySpinner(mResponse);

    final List<LoanPurposeOptions> loanPurposeOptionsType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> loanPurposeOptionsTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("loanPurposeOptions")) {
            JSONArray loanPurposeOptionsTypes = obj.getJSONArray("loanPurposeOptions");
            for (int i = 0; i < loanPurposeOptionsTypes.length(); i++) {
                JSONObject loanPurposeOptionsTypesObject = loanPurposeOptionsTypes.getJSONObject(i);
                LoanPurposeOptions loanpurpose = new LoanPurposeOptions();
                loanpurpose.setId(loanPurposeOptionsTypesObject.optInt("id"));
                loanpurpose.setName(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeOptionsType.add(loanpurpose);
                loanPurposeOptionsTypeNames.add(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeNameIdHashMap.put(loanpurpose.getName(), loanpurpose.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> loanPTypeAdapter = new ArrayAdapter<>(getActivity(), layout.simple_spinner_item,
            loanPurposeOptionsTypeNames);

    loanPTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_loan_purpose.setAdapter(loanPTypeAdapter);
    sp_loan_purpose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            loanPurposeId = loanPurposeNameIdHashMap.get(loanPurposeOptionsTypeNames.get(i));
            Log.d("loanpurpose" + loanPurposeOptionsTypeNames.get(i), String.valueOf(loanPurposeId));
            if (loanPurposeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.basetechnology.s0.agentserver.field.StringField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type").toLowerCase();
    if (type == null || !type.equals("string"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null;
    int minLength = fieldJson.has("min_length") ? fieldJson.optInt("min_length") : 0;
    int maxLength = fieldJson.has("max_length") ? fieldJson.optInt("max_length") : 0;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String validRegex = fieldJson.has("valid_regex") ? fieldJson.optString("valid_regex") : null;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new StringField(symbolTable, name, label, description, defaultValue, minLength, maxLength,
            nominalWidth, validRegex, compute);
}

From source file:net.dv8tion.jda.core.handle.PresenceUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    //Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked.
    if (content.has("guild_id")) {
        final long guildId = content.getLong("guild_id");
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }/*from   w  w  w .j a v  a  2  s.  c om*/

    JSONObject jsonUser = content.getJSONObject("user");
    final long userId = jsonUser.getLong("id");
    UserImpl user = (UserImpl) api.getUserMap().get(userId);

    //If we do know about the user, lets update the user's specific info.
    // Afterwards, we will see if we already have them cached in the specific guild
    // or Relation. If not, we'll cache the OnlineStatus and Game for later handling
    // unless OnlineStatus is OFFLINE, in which case we probably received this event
    // due to a User leaving a guild or no longer being a relation.
    if (user != null) {
        if (jsonUser.has("username")) {
            String name = jsonUser.getString("username");
            String discriminator = jsonUser.get("discriminator").toString();
            String avatarId = jsonUser.isNull("avatar") ? null : jsonUser.getString("avatar");

            if (!user.getName().equals(name)) {
                String oldUsername = user.getName();
                String oldDiscriminator = user.getDiscriminator();
                user.setName(name);
                user.setDiscriminator(discriminator);
                api.getEventManager().handle(
                        new UserNameUpdateEvent(api, responseNumber, user, oldUsername, oldDiscriminator));
            }
            String oldAvatar = user.getAvatarId();
            if (!(avatarId == null && oldAvatar == null) && !Objects.equals(avatarId, oldAvatar)) {
                String oldAvatarId = user.getAvatarId();
                user.setAvatarId(avatarId);
                api.getEventManager().handle(new UserAvatarUpdateEvent(api, responseNumber, user, oldAvatarId));
            }
        }

        //Now that we've update the User's info, lets see if we need to set the specific Presence information.
        // This is stored in the Member or Relation objects.
        String gameName = null;
        String gameUrl = null;
        Game.GameType type = null;
        if (!content.isNull("game") && !content.getJSONObject("game").isNull("name")) {
            gameName = content.getJSONObject("game").get("name").toString();
            gameUrl = (content.getJSONObject("game").isNull("url") ? null
                    : content.getJSONObject("game").get("url").toString());
            try {
                type = content.getJSONObject("game").isNull("type") ? Game.GameType.DEFAULT
                        : Game.GameType.fromKey(
                                Integer.parseInt(content.getJSONObject("game").get("type").toString()));
            } catch (NumberFormatException ex) {
                type = Game.GameType.DEFAULT;
            }
        }
        Game nextGame = (gameName == null ? null : new GameImpl(gameName, gameUrl, type));
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));

        //If we are in a Guild, then we will use Member.
        // If we aren't we'll be dealing with the Relation system.
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            MemberImpl member = (MemberImpl) guild.getMember(user);

            //If the Member is null, then User isn't in the Guild.
            //This is either because this PRESENCE_UPDATE was received before the GUILD_MEMBER_ADD event
            // or because a Member recently left and this PRESENCE_UPDATE came after the GUILD_MEMBER_REMOVE event.
            //If it is because a Member recently left, then the status should be OFFLINE. As such, we will ignore
            // the event if this is the case. If the status isn't OFFLINE, we will cache and use it when the
            // Member object is setup during GUILD_MEMBER_ADD
            if (member == null) {
                //Cache the presence and return to finish up.
                if (status != OnlineStatus.OFFLINE) {
                    guild.getCachedPresenceMap().put(userId, content);
                    return null;
                }
            } else {
                //The member is already cached, so modify the presence values and fire events as needed.
                if (!member.getOnlineStatus().equals(status)) {
                    OnlineStatus oldStatus = member.getOnlineStatus();
                    member.setOnlineStatus(status);
                    api.getEventManager().handle(
                            new UserOnlineStatusUpdateEvent(api, responseNumber, user, guild, oldStatus));
                }
                if (member.getGame() == null ? nextGame != null : !member.getGame().equals(nextGame)) {
                    Game oldGame = member.getGame();
                    member.setGame(nextGame);
                    api.getEventManager()
                            .handle(new UserGameUpdateEvent(api, responseNumber, user, guild, oldGame));
                }
            }
        } else {
            //In this case, this PRESENCE_UPDATE is for a Relation.

        }
    } else {
        //In this case, we don't have the User cached, which means that we can't update the User's information.
        // This is most likely because this PRESENCE_UPDATE came before the GUILD_MEMBER_ADD that would have added
        // this User to our User cache. Or, it could have come after a GUILD_MEMBER_REMOVE that caused the User
        // to be removed from JDA's central User cache because there were no more connected Guilds. If this is
        // the case, then the OnlineStatus will be OFFLINE and we can ignore this event.
        //Either way, we don't have the User cached so we need to cache the Presence information if
        // the OnlineStatus is not OFFLINE.

        //If the OnlineStatus is OFFLINE, ignore the event and return.
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
        if (status == OnlineStatus.OFFLINE)
            return null;

        //If this was for a Guild, cache it in the Guild for later use in GUILD_MEMBER_ADD
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            guild.getCachedPresenceMap().put(userId, content);
        } else {
            //cache in relationship stuff
        }
    }
    return null;
}

From source file:com.googlecode.goclipse.tooling.oracle.OraclePackageDescribeParser.java

protected JSONArray getOptionalJSONArray(JSONObject packageObj, String key) throws JSONException {
    if (!packageObj.has(key)) {
        return null;
    }//from w w w .  j a v  a2  s  .  c  o m
    return packageObj.getJSONArray(key);
}

From source file:com.wei.c.im.test.msg.data.receive.MsgReceived.java

@Override
public boolean isBelongToMe(JSONObject json) {
    return !json.has(KEY_TYPE); //type??type
}

From source file:cgeo.geocaching.connector.gc.GCParser.java

public static SearchResult searchByAddress(final String address, final CacheType cacheType,
        final boolean showCaptcha, RecaptchaReceiver recaptchaReceiver) {
    if (StringUtils.isBlank(address)) {
        Log.e("GCParser.searchByAddress: No address given");
        return null;
    }/*from   w w w .j  a v  a  2s. c  o  m*/
    try {
        final JSONObject response = Network.requestJSON("http://www.geocaching.com/api/geocode",
                new Parameters("q", address));
        if (response == null) {
            return null;
        }
        if (!StringUtils.equalsIgnoreCase(response.getString("status"), "success")) {
            return null;
        }
        if (!response.has("data")) {
            return null;
        }
        final JSONObject data = response.getJSONObject("data");
        if (data == null) {
            return null;
        }
        return searchByCoords(new Geopoint(data.getDouble("lat"), data.getDouble("lng")), cacheType,
                showCaptcha, recaptchaReceiver);
    } catch (final JSONException e) {
        Log.w("GCParser.searchByAddress", e);
    }

    return null;
}