Example usage for com.google.gson JsonObject get

List of usage examples for com.google.gson JsonObject get

Introduction

In this page you can find the example usage for com.google.gson JsonObject get.

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:com.agwego.common.GsonHelper.java

License:Open Source License

/**
 * Short hand, encapsulate the check if the object has the key and return the appropriate Boolean, otherwise the
 * default value//from  w ww . j  a v  a2s. c om
 *
 * @param jObject the JsonObject in question
 * @param key the key to lookup
 * @param otherwise - if the key doesn't exist
 * @return the value for key as a Boolean
 */
public static Boolean getAsBoolean(final JsonObject jObject, final String key, final Boolean otherwise) {
    return jObject.has(key) ? jObject.get(key).getAsBoolean() : otherwise;
}

From source file:com.ai2020lab.aiutils.common.JsonUtils.java

License:Apache License

/**
 * ?JSONObject??Stringvalue/* w w  w  .  j av  a 2  s . c om*/
 *
 * @param key ??
 * @return ??value
 */
public String getObjStringValue(String key, JsonObject obj) {
    if (key == null || key.equals("")) {
        // Key
        throw new IllegalArgumentException("?key?");
    }
    if (obj == null || !obj.isJsonObject()) {
        // JsonObject??JsonObject
        throw new IllegalArgumentException("?obj?JsonObject?");
    }
    if (!obj.has(key)) {
        // Key
        LogUtils.e(TAG, "objkey'" + key + "' ");
        return null;
    }
    return obj.get(key).getAsString();
}

From source file:com.ai2020lab.aiutils.common.JsonUtils.java

License:Apache License

/**
 * ?JSONObject??Integervalue/*from  w ww  .java  2s.c  om*/
 *
 * @param key ??
 * @return ??value
 */
public Integer getObjIntValue(String key, JsonObject obj) {
    if (key == null || key.equals("")) {
        // Key
        throw new IllegalArgumentException("?key?");
    }
    if (obj == null || !obj.isJsonObject()) {
        // JsonObject??JsonObject
        throw new IllegalArgumentException("?obj?JsonObject?");
    }
    if (!obj.has(key)) {
        // Key
        LogUtils.e(TAG, "objkey'" + key + "' ");
        return null;
    }
    return obj.get(key).getAsInt();
}

From source file:com.alfresco.client.api.core.model.deserializer.FavoriteEntryDeserializer.java

License:Apache License

@Override
public FavoriteRepresentation deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException {
    JsonElement entry = je;//from w  ww  . ja v  a2 s.  c  om
    if (je.getAsJsonObject().has(PublicAPIConstant.ENTRY_VALUE)) {
        entry = je.getAsJsonObject().get(PublicAPIConstant.ENTRY_VALUE);
    }

    FavoriteRepresentation favorite = null;
    JsonObject target = entry.getAsJsonObject().get("target").getAsJsonObject();
    if (target.has("file")) {
        favorite = jdc.deserialize(entry, FavoriteNodeRepresentation.class);
        NodeRepresentation file = jdc.deserialize(target.get("file").getAsJsonObject(),
                NodeRepresentation.class);
        favorite.setTarget(file);
    } else if (target.has("folder")) {
        favorite = jdc.deserialize(entry, FavoriteNodeRepresentation.class);
        NodeRepresentation file = jdc.deserialize(target.get("folder").getAsJsonObject(),
                NodeRepresentation.class);
        favorite.setTarget(file);
    } else if (target.has("site")) {
        favorite = jdc.deserialize(entry, FavoriteSiteRepresentation.class);
        SiteRepresentation site = jdc.deserialize(target.get("site").getAsJsonObject(),
                SiteRepresentation.class);
        favorite.setTarget(site);
    }

    return favorite;
}

From source file:com.aliyun.odps.udf.utils.CounterUtils.java

License:Apache License

private static void fromJson(CounterGroup group, JsonObject obj) {
    JsonArray counterArray = obj.get("counters").getAsJsonArray();
    for (int i = 0; i < counterArray.size(); i++) {
        JsonObject subObj = counterArray.get(i).getAsJsonObject();
        String counterName = subObj.get("name").getAsString();
        Counter counter = group.findCounter(counterName);
        long value = subObj.get("value").getAsLong();
        counter.increment(value);/*from   w w  w .  jav a2s  .  c o  m*/
    }
}

From source file:com.amazonaws.apigatewaydemo.RequestRouter.java

License:Open Source License

/**
 * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the
 * "action" property to decide where to route the request. The "body" property of the incoming request is passed
 * to the DemoAction implementation as a request body.
 *
 * @param request  The InputStream for the incoming event. This should contain an "action" and "body" properties. The
 *                 action property should contain the namespaced name of the class that should handle the invocation.
 *                 The class should implement the DemoAction interface. The body property should contain the full
 *                 request body for the action class.
 * @param response An OutputStream where the response returned by the action class is written
 * @param context  The Lambda Context object
 * @throws BadRequestException    This Exception is thrown whenever parameters are missing from the request or the action
 *                                class can't be found
 * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database
 *                                is not accessible
 *///from   ww  w . j a v  a  2s.c  o m
public static void lambdaHandler(InputStream request, OutputStream response, Context context)
        throws BadRequestException, InternalErrorException {
    LambdaLogger logger = context.getLogger();

    JsonParser parser = new JsonParser();
    JsonObject inputObj;
    try {
        inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject();
    } catch (IOException e) {
        logger.log("Error while reading request\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (inputObj == null || inputObj.get("action") == null
            || inputObj.get("action").getAsString().trim().equals("")) {
        logger.log("Invald inputObj, could not find action parameter");
        throw new BadRequestException("Could not find action value in request");
    }

    String actionClass = inputObj.get("action").getAsString();
    DemoAction action;

    try {
        action = DemoAction.class.cast(Class.forName(actionClass).newInstance());
    } catch (final InstantiationException e) {
        logger.log("Error while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final IllegalAccessException e) {
        logger.log("Illegal access while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final ClassNotFoundException e) {
        logger.log("Action class could not be found\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (action == null) {
        logger.log("Action class is null");
        throw new BadRequestException("Invalid action class");
    }

    JsonObject body = null;
    if (inputObj.get("body") != null) {
        body = inputObj.get("body").getAsJsonObject();
    }

    String output = action.handle(body, context);

    try {
        IOUtils.write(output, response);
    } catch (final IOException e) {
        logger.log("Error while writing response\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

License:Mozilla Public License

/**
 * Populate overzicht fragment from local member vars
 *//*from  w w  w.ja  v  a 2s . c o m*/
private void populateOverzichtFragment() {
    if (mOverzichtFragmentReady) {

        // TODO: show the changes in case we are editing an existing dagvergunning

        // koopman
        if (mKoopmanId > 0) {
            mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.VISIBLE);
            mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.GONE);

            // koopman details
            mOverzichtFragment.setKoopman(mKoopmanId);

            // dagvergunning registratie tijd
            if (mRegistratieDatumtijd != null) {
                try {
                    Date registratieDate = new SimpleDateFormat(getString(R.string.date_format_datumtijd),
                            Locale.getDefault()).parse(mRegistratieDatumtijd);
                    SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_tijd));
                    String registratieTijd = sdf.format(registratieDate);
                    mOverzichtFragment.mRegistratieDatumtijdText.setText(registratieTijd);
                } catch (java.text.ParseException e) {
                    Utility.log(getContext(), LOG_TAG, "Format registratie tijd failed: " + e.getMessage());
                }
            } else {
                mOverzichtFragment.mRegistratieDatumtijdText.setText("");
            }

            // dagvergunning notitie
            if (mNotitie != null && !mNotitie.equals("")) {
                mOverzichtFragment.mNotitieText.setText(getString(R.string.label_notitie) + ": " + mNotitie);
                Utility.collapseView(mOverzichtFragment.mNotitieText, false);
            } else {
                Utility.collapseView(mOverzichtFragment.mNotitieText, true);
            }

            // dagvergunning totale lengte
            if (mTotaleLengte != -1) {
                mOverzichtFragment.mTotaleLengte
                        .setText(mTotaleLengte + " " + getString(R.string.length_meter));
            }

            // registratie account naam
            if (mRegistratieAccountNaam != null) {
                mOverzichtFragment.mAccountNaam.setText(mRegistratieAccountNaam);
            } else {
                mOverzichtFragment.mAccountNaam.setText("");
            }

            // koopman aanwezig status
            if (mKoopmanAanwezig != null) {

                // get the corresponding aanwezig title from the resource array based on the aanwezig key
                String[] aanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key);
                String[] aanwezigTitles = getResources().getStringArray(R.array.array_aanwezig_title);
                String aanwezigTitle = "";
                for (int i = 0; i < aanwezigKeys.length; i++) {
                    if (aanwezigKeys[i].equals(mKoopmanAanwezig)) {
                        aanwezigTitle = aanwezigTitles[i];
                    }
                }
                mOverzichtFragment.mAanwezigText.setText(aanwezigTitle);
            }

            // vervanger
            if (mVervangerId > 0) {

                // hide the aanwezig status and populate and show the vervanger details
                mOverzichtFragment.mAanwezigText.setVisibility(View.GONE);
                mOverzichtFragment.mVervangerDetail.setVisibility(View.VISIBLE);
                mOverzichtFragment.setVervanger(mVervangerId);
            } else {

                // show the aanwezig status and hide the vervanger details
                mOverzichtFragment.mAanwezigText.setVisibility(View.VISIBLE);
                mOverzichtFragment.mVervangerDetail.setVisibility(View.GONE);
            }
        } else {
            mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.VISIBLE);
            mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.GONE);
        }

        // product
        if (mErkenningsnummer != null && isProductSelected()) {

            // show progress bar
            mProgressbar.setVisibility(View.VISIBLE);

            // disable save function until we have a response from the api for a concept factuur
            mConceptFactuurDownloaded = false;

            // post the dagvergunning details to the api and retrieve a concept 'factuur'
            ApiPostDagvergunningConcept postDagvergunningConcept = new ApiPostDagvergunningConcept(
                    getContext());
            postDagvergunningConcept.setPayload(dagvergunningToJson());
            postDagvergunningConcept.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Response<JsonObject> response) {

                    // hide progress bar
                    mProgressbar.setVisibility(View.GONE);

                    if (response.isSuccess() && response.body() != null) {
                        mOverzichtFragment.mProductenLinearLayout.setVisibility(View.VISIBLE);
                        mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.GONE);

                        // enable save function and give wizard next button background enabled color
                        mConceptFactuurDownloaded = true;
                        mWizardNextButton
                                .setBackgroundColor(ContextCompat.getColor(getContext(), R.color.accent));

                        // from the response, populate the product section of the overzicht fragment
                        View overzichtView = mOverzichtFragment.getView();
                        if (overzichtView != null) {

                            // find placeholder table layout view
                            TableLayout placeholderLayout = (TableLayout) overzichtView
                                    .findViewById(R.id.producten_placeholder);
                            if (placeholderLayout != null) {
                                placeholderLayout.removeAllViews();
                                LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                                // get the producten array
                                JsonArray producten = response.body().getAsJsonArray(getString(
                                        R.string.makkelijkemarkt_api_dagvergunning_concept_producten));

                                if (producten != null) {
                                    int rowCount = 0;

                                    // table header
                                    View headerLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView btwHeaderText = (TextView) headerLayout
                                            .findViewById(R.id.btw_totaal);
                                    btwHeaderText.setText("BTW");
                                    TextView exclusiefHeaderText = (TextView) headerLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    exclusiefHeaderText.setText("Ex. BTW");
                                    placeholderLayout.addView(headerLayout, rowCount++);

                                    for (int i = 0; i < producten.size(); i++) {
                                        JsonObject product = producten.get(i).getAsJsonObject();

                                        // get the product item layout
                                        View childLayout = layoutInflater
                                                .inflate(R.layout.dagvergunning_overzicht_product_item, null);

                                        // aantal
                                        if (product.get("aantal") != null
                                                && !product.get("aantal").isJsonNull()) {
                                            TextView aantalText = (TextView) childLayout
                                                    .findViewById(R.id.product_aantal);
                                            aantalText.setText(product.get("aantal").getAsInt() + " x ");
                                        }

                                        // naam
                                        if (product.get("naam") != null && !product.get("naam").isJsonNull()) {
                                            TextView naamText = (TextView) childLayout
                                                    .findViewById(R.id.product_naam);
                                            naamText.setText(
                                                    Utility.capitalize(product.get("naam").getAsString()));
                                        }

                                        // btw %
                                        if (product.get("btw_percentage") != null
                                                && !product.get("btw_percentage").isJsonNull()) {
                                            long btwPercentage = Math.round(Double
                                                    .parseDouble(product.get("btw_percentage").getAsString()));
                                            if (btwPercentage != 0) {
                                                TextView btwPercentageText = (TextView) childLayout
                                                        .findViewById(R.id.btw_percentage);
                                                btwPercentageText.setText(btwPercentage + "%");
                                            }
                                        }

                                        // btw totaal
                                        if (product.get("btw_totaal") != null
                                                && !product.get("btw_totaal").isJsonNull()) {
                                            double btwTotaalProduct = Double
                                                    .parseDouble(product.get("btw_totaal").getAsString());
                                            TextView btwTotaalText = (TextView) childLayout
                                                    .findViewById(R.id.btw_totaal);
                                            if (Math.round(btwTotaalProduct) != 0) {
                                                btwTotaalText
                                                        .setText(String.format(" %.2f", btwTotaalProduct));
                                            } else {
                                                btwTotaalText.setText("-");
                                            }
                                        }

                                        // bedrag totaal
                                        if (product.get("totaal") != null
                                                && !product.get("totaal").isJsonNull()) {
                                            double bedragTotaal = Double
                                                    .parseDouble(product.get("totaal").getAsString());
                                            TextView bedragTotaalText = (TextView) childLayout
                                                    .findViewById(R.id.bedrag_totaal);
                                            bedragTotaalText.setText(String.format(" %.2f", bedragTotaal));
                                        }

                                        // add child view
                                        placeholderLayout.addView(childLayout, rowCount++);
                                    }

                                    // exclusief
                                    double exclusief = 0;
                                    if (response.body().get("exclusief") != null
                                            && !response.body().get("exclusief").isJsonNull()) {
                                        exclusief = Double
                                                .parseDouble(response.body().get("exclusief").getAsString());
                                    }

                                    // totaal
                                    double totaal = 0;
                                    if (response.body().get("totaal") != null
                                            && !response.body().get("totaal").isJsonNull()) {
                                        totaal = response.body().get("totaal").getAsDouble();
                                    }

                                    // totaal btw en ex. btw
                                    View totaalLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView naamText = (TextView) totaalLayout.findViewById(R.id.product_naam);
                                    naamText.setText("Totaal");
                                    TextView btwTotaalText = (TextView) totaalLayout
                                            .findViewById(R.id.btw_totaal);
                                    if (Math.round(totaal - exclusief) != 0) {
                                        btwTotaalText.setText(String.format(" %.2f", (totaal - exclusief)));
                                    }
                                    TextView exclusiefText = (TextView) totaalLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    exclusiefText.setText(String.format(" %.2f", exclusief));
                                    placeholderLayout.addView(totaalLayout, rowCount++);

                                    // separator
                                    View emptyLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    placeholderLayout.addView(emptyLayout, rowCount++);

                                    // totaal inc. btw
                                    View totaalIncLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView totaalNaamText = (TextView) totaalIncLayout
                                            .findViewById(R.id.product_naam);
                                    totaalNaamText.setText("Totaal inc. BTW");
                                    TextView totaalIncText = (TextView) totaalIncLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    totaalIncText.setText(String.format(" %.2f", totaal));
                                    placeholderLayout.addView(totaalIncLayout, rowCount);
                                }
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    mProgressbar.setVisibility(View.GONE);
                }
            });
        } else {
            mOverzichtFragment.mProductenLinearLayout.setVisibility(View.GONE);

            if (mKoopmanId > 0) {
                mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.VISIBLE);
            }
        }
    }
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.Utility.java

License:Mozilla Public License

/**
 * Check if there is a newer build of the app available
 *///ww  w . j a va2s  .c  o m
public static void checkForUpdate(final Activity activity, final String fragmentTag, final boolean silent) {

    // get the latest android build number from the api version call
    ApiGetVersion getVersion = new ApiGetVersion(activity);
    getVersion.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Response<JsonObject> response) {
            if (response.isSuccess() && response.body() != null) {
                long versionCode = 0;
                long androidBuild = 0;

                // get androidBuild from api response
                try {
                    JsonObject versionInfo = response.body().getAsJsonObject();
                    if (versionInfo != null
                            && versionInfo.get(activity.getString(
                                    R.string.makkelijkemarkt_api_version_app_android_build_name)) != null
                            && !versionInfo
                                    .get(activity.getString(
                                            R.string.makkelijkemarkt_api_version_app_android_build_name))
                                    .isJsonNull()) {
                        androidBuild = versionInfo
                                .get(activity
                                        .getString(R.string.makkelijkemarkt_api_version_app_android_build_name))
                                .getAsLong();
                    } else {
                        Log.e(Utility.class.getSimpleName(), "androidBuild not found in VersionInfo");
                    }
                } catch (IllegalStateException e) {
                    Log.e(Utility.class.getSimpleName(), "VersionInfo not found: " + e.getMessage());
                }

                // get the versionCode of the currently installed app
                final String appPackageName = activity.getPackageName();
                try {
                    PackageInfo info = activity.getPackageManager().getPackageInfo(appPackageName, 0);
                    versionCode = info.versionCode;
                } catch (Exception e) {
                    Log.e(Utility.class.getSimpleName(), "PackageInfo not found: " + e.getMessage());
                }

                // check if androidBuild is higher than current versionCode
                if (versionCode > 0 && androidBuild > 0 && androidBuild > versionCode) {

                    // show a modal dialog with an app update notice that will open the play store app
                    DialogFragment updateFragment = UpdateAvailableDialogFragment.newInstance(appPackageName);
                    updateFragment.setCancelable(false);
                    updateFragment.show(activity.getFragmentManager(), fragmentTag);
                } else if (!silent) {
                    showToast(activity, new Toast(activity),
                            activity.getString(R.string.dialog_app_update_not_available));
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e(Utility.class.getSimpleName(), "Failed to retrieve the version info");
        }
    });
}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

private void authentication(String userName, String apiKey) throws IOException {
    String json = generateToken(userName, apiKey);

    JsonParser jsonParser = new JsonParser();
    JsonObject jo = (JsonObject) jsonParser.parse(json);

    setToken(jo.getAsJsonObject("access").getAsJsonObject("generateToken").get("id").getAsString());
    JsonArray services = jo.getAsJsonObject("access").get("serviceCatalog").getAsJsonArray();

    for (JsonElement jsonElement : services) {
        JsonObject jobj = jsonElement.getAsJsonObject();

        if (jobj.get("name").getAsString().equals("cloudFiles")) {

            JsonArray endpoints = jobj.getAsJsonArray("endpoints");
            for (JsonElement jsonElement2 : endpoints) {

                urls.put(jsonElement2.getAsJsonObject().get("region").getAsString(),
                        jsonElement2.getAsJsonObject().get("publicURL").getAsString());

            }// w  w  w .j a  v  a  2  s  . com
        }

        if (jobj.get("name").getAsString().equals("cloudFilesCDN")) {

            JsonArray endpoints = jobj.getAsJsonArray("endpoints");
            for (JsonElement jsonElement2 : endpoints) {

                cdnUrls.put(jsonElement2.getAsJsonObject().get("region").getAsString(),
                        jsonElement2.getAsJsonObject().get("publicURL").getAsString());

            }
        }

    }

}

From source file:com.android.tools.idea.editors.hierarchyview.HierarchyViewCaptureOptions.java

License:Apache License

public void parse(String json) {
    JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
    setVersion(obj.get(VERSION).getAsInt());
    setTitle(obj.get(TITLE).getAsString());
}