Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.pmeade.arya.gson.deserialize.ParameterizedFieldDeserializer.java

License:Open Source License

/**
 * Request deserialization of a JSON array into a Collection<V> or
 * deserialization of a JSON object into a Map<K,V>. The deserialized
 * object will be populated in the provided field on the provided Object.
 * @param jo JsonObject containing the JSON to be deserialized
 * @param t Object to be populated with the parameterized content
 * @param field Field of the object to be populated (also identifies the
 *              name of the JSON to be deserialized)
 * @throws IllegalAccessException never thrown (you don't actually believe
 *                                what I just told you, right?)
 *//*from   www. j  a  v a 2s  . c  o  m*/
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException {
    // if the provided JsonObject has JSON data mapped for the field
    if (jo.has(field.getName())) {
        // obtain the raw parameterized type (Collection, Map, etc.)
        ParameterizedType paraType = (ParameterizedType) field.getGenericType();
        Class rawType = (Class) paraType.getRawType();
        // if the raw type is assignable to Collection
        if (Collection.class.isAssignableFrom(rawType)) {
            // assume the JSON data is an array, and obtain in that format
            JsonArray ja = jo.getAsJsonArray(field.getName());
            // deserialize the JSON array into a Collection object and
            // populate the field in the provided object
            field.set(t, deserializeCollection(ja, paraType));
        }
        // otherwise, if the raw type is assignable to Map
        else if (Map.class.isAssignableFrom(rawType)) {
            // assume the JSON data is a JSON object, and obtain that
            JsonObject jo2 = jo.getAsJsonObject(field.getName());
            // deserialize the JSON object into a Map object and
            // populate the field in the provided object
            field.set(t, deserializeMap(jo2, paraType));
        }
        // otherwise, these aren't the droids we're looking for
        else {
            // we can go about our business ... move along
            throw new UnsupportedOperationException();
        }
    }
}

From source file:com.podio.sdk.push.FayePushClient.java

License:Open Source License

private JsonObject getJsonObject(JsonObject parent, String member) {
    return parent != null && parent.has(member) ? parent.getAsJsonObject(member) : new JsonObject();
}

From source file:com.popdeem.sdk.core.deserializer.PDFeedDeserializer.java

License:Open Source License

@Override
public PDFeed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    PDFeed feed = gson.fromJson(json, typeOfT);

    JsonObject feedObject = json.getAsJsonObject();
    // Brand/*from   ww w  .  ja  va  2s .  c o  m*/
    if (feedObject.has("brand")) {
        JsonObject brandObject = feedObject.getAsJsonObject("brand");
        feed.setBrandName(brandObject.get("name").getAsString());
        feed.setBrandLogoUrlString(brandObject.get("logo").getAsString());
    }

    // Reward
    if (feedObject.has("reward")) {
        JsonObject brandObject = feedObject.getAsJsonObject("reward");
        //            feed.setRewardTypeString(brandObject.get("type").getAsString());
        feed.setDescriptionString(brandObject.get("description").getAsString());
    }

    // Social Account
    if (feedObject.has("social_account")) {
        JsonObject socialObject = feedObject.getAsJsonObject("social_account");
        if (socialObject.has("profile_picture")) {
            feed.setUserProfilePicUrlString(socialObject.get("profile_picture").getAsString());
        }

        if (socialObject.has("user")) {
            JsonObject userObject = socialObject.getAsJsonObject("user");
            feed.setUserId(userObject.get("id").getAsInt());
            if (userObject.has("first_name") && !userObject.get("first_name").isJsonNull()) {
                feed.setUserFirstName(userObject.get("first_name").getAsString());
            }
            if (userObject.has("last_name") && !userObject.get("last_name").isJsonNull()) {
                feed.setUserLastName(userObject.get("last_name").getAsString());
            }
        }
    }

    //        feed.setTimeAgo(feedObject.get("time_ago").getAsString());
    //        feed.setImageUrlString(feedObject.get("picture=").getAsString());
    //        feed.setActionText(feedObject.get("text").getAsString());

    return feed;
}

From source file:com.popdeem.sdk.core.deserializer.PDSocialAccountFacebookDeserializer.java

License:Open Source License

@Override
public PDUserFacebook deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    PDUserFacebook socialAccountFacebook = gson.fromJson(json, typeOfT);

    JsonObject jsonObject = json.getAsJsonObject();
    if (jsonObject.has("score")) {
        JsonObject scoreObject = jsonObject.getAsJsonObject("score");

        // Total Score
        if (scoreObject.has("total_score")) {
            JsonObject totalScoreObject = scoreObject.getAsJsonObject("total_score");
            if (totalScoreObject.has("value")) {
                socialAccountFacebook.setTotalScore(totalScoreObject.get("value").getAsString());
            }//from w w  w  .  j ava2s.  c  om
        }

        // influence score
        if (scoreObject.has("influence_score")) {
            JsonObject influenceScoreObject = scoreObject.getAsJsonObject("influence_score");
            if (influenceScoreObject.has("reach_score_value")) {
                socialAccountFacebook
                        .setInfluenceReachScore(influenceScoreObject.get("reach_score_value").getAsString());
            }
            if (influenceScoreObject.has("engagement_score_value")) {
                socialAccountFacebook.setInfluenceEngagementScore(
                        influenceScoreObject.get("engagement_score_value").getAsString());
            }
            if (influenceScoreObject.has("frequency_score_value")) {
                socialAccountFacebook.setInfluenceFrequencyScore(
                        influenceScoreObject.get("frequency_score_value").getAsString());
            }
        }

        // advocacy score
        if (scoreObject.has("advocacy_score")) {
            JsonObject advocacyScoreObject = scoreObject.getAsJsonObject("advocacy_score");
            if (advocacyScoreObject.has("value")) {
                socialAccountFacebook.setAdvocacyScore(advocacyScoreObject.get("value").getAsInt());
            }
        }
    }

    return socialAccountFacebook;
}

From source file:com.popdeem.sdk.core.deserializer.PDSocialMediaFriendDeserializer.java

License:Open Source License

@Override
public PDSocialMediaFriend deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    JsonObject jsonObject = json.getAsJsonObject();
    PDSocialMediaFriend friend = gson.fromJson(jsonObject, PDSocialMediaFriend.class);
    if (jsonObject.has("picture")) {
        JsonObject pictureObject = jsonObject.getAsJsonObject("picture");
        if (pictureObject.has("data")) {
            JsonObject pictureDataObject = pictureObject.getAsJsonObject("data");
            friend.setImageUrl(pictureDataObject.get("url").getAsString());
        }/*from  w ww.j  ava 2 s .  co m*/
    }
    return friend;
}

From source file:com.popdeem.sdk.core.PopdeemSDK.java

License:Open Source License

/**
 * Initialize Popdeem SDK//w  w w  . ja v  a 2s .c om
 *
 * @param application Application context
 * @param enviroment Popdeem enviroment PD_PROD_API_ENDPOINT, PD_STAGING_API_ENDPOINT
 *
 */
public static void initializeSDK(@NonNull final Application application, String enviroment) {

    application.registerReceiver(mLoggedInBroadcastReceiver, new IntentFilter(PD_LOGGED_IN_RECEIVER_FILTER));

    PDAPIConfig.PD_API_ENDPOINT = enviroment;
    sApplication = application;

    // Register Activity Lifecycle Callbacks
    application.registerActivityLifecycleCallbacks(PD_ACTIVITY_LIFECYCLE_CALLBACKS);

    // Init Realm
    PDRealmUtils.initRealmDB(application);

    TwitterAuthConfig authConfig = PDSocialUtils.getTwitterAuthConfig(application.getApplicationContext());

    TwitterConfig config = new TwitterConfig.Builder(application).logger(new DefaultLogger(Log.DEBUG))
            .twitterAuthConfig(authConfig).debug(true).build();
    Twitter.initialize(config);

    // Get Popdeem API Key
    getPopdeemAPIKey();
    FacebookSdk.sdkInitialize(application, new FacebookSdk.InitializeCallback() {
        @Override
        public void onInitialized() {
            Log.i("Facebook", "onInitialized: Facebook initialized");
        }
    });

    sdkInitialized = true;

    PDAPIClient.instance().getCustomer(new PDAPICallback<JsonObject>() {
        @Override
        public void success(JsonObject jsonObject) {
            Log.i("JsonObject", "success: ");
            if (jsonObject.has("customer")) {
                JsonObject customer = jsonObject.getAsJsonObject("customer");
                PDRealmCustomer realmCustomer = PDRealmCustomer.fromJson(customer);

                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                RealmResults<PDRealmCustomer> results = realm.where(PDRealmCustomer.class).findAll();
                results.deleteAllFromRealm();
                realm.copyToRealm(realmCustomer);
                realm.commitTransaction();
                realm.close();
                initFromCustomer(application);

            }
        }

        @Override
        public void failure(int statusCode, Exception e) {
            e.printStackTrace();
            initFromCustomer(application);

        }
    });

    // Get UID for Non Social login
    if (PDUniqueIdentifierUtils.getUID() == null) {
        PDUniqueIdentifierUtils.createUID(application, new PDUniqueIdentifierUtils.PDUIDCallback() {
            @Override
            public void success(String uid) {
                PDRealmNonSocialUID uidReam = new PDRealmNonSocialUID();
                //                    uidReam.setId(0);
                uidReam.setRegistered(false);
                uidReam.setUid(uid);

                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(uidReam);
                realm.commitTransaction();
                realm.close();

                registerNonSocialUser();
            }

            @Override
            public void failure(String message) {
                PDLog.d(PDUniqueIdentifierUtils.class, "failed to create uid: " + message);
            }
        });
    }

    // Init GCM
    PDFirebaseMessagingService.initGCM(application, new PDGCMUtils.PDGCMRegistrationCallback() {
        @Override
        public void success(String registrationToken) {
            PDLog.d(PDGCMUtils.class, "Init GCM success. Registration token: " + registrationToken);
            registerNonSocialUser();
        }

        @Override
        public void failure(String message) {
            PDLog.d(PDGCMUtils.class, "Init GCM failure: " + message);
        }
    });

}

From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java

License:Open Source License

private void verifyReward() {

    PDAPIClient.instance().verifyInstagramPostForReward(mReward.getId(), new PDAPICallback<JsonObject>() {
        @Override//from  w  w  w  .j  a v a  2s. co m
        public void success(JsonObject jsonObject) {
            PDLog.d(PDUIClaimActivity.class, "verify success: " + jsonObject.toString());
            boolean success = false;
            if (jsonObject.has("data")) {
                JsonObject dataObject = jsonObject.getAsJsonObject("data");
                if (dataObject.has("status")) {
                    success = dataObject.get("status").getAsString().equalsIgnoreCase("success");
                }
            }
            if (success) {
                mReward.setInstagramVerified(true);
            }
            mReward.setVerifying(false);
        }

        @Override
        public void failure(int statusCode, Exception e) {
            PDLog.d(PDUIWalletFragment.class,
                    "verify failed: code=" + statusCode + ", message=" + e.getMessage());
            mReward.setVerifying(false);
        }
    });
}

From source file:com.popdeem.sdk.uikit.fragment.PDUIHomeFlowFragment.java

License:Open Source License

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_pd_home_flow, container, false);

    //        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.pd_home_inbox_fab);
    //        fab.setImageDrawable(PDUIColorUtils.getInboxButtonIcon(getActivity()));
    //        fab.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View view) {
    //                startActivity(new Intent(getActivity(), PDUIInboxActivity.class));
    //            }
    //        });
    //        fab.setVisibility(View.GONE);
    ///*from  w w  w . ja  va 2 s  . c o m*/
    //        ImageButton settingsButton = (ImageButton) view.findViewById(R.id.pd_home_flow_settings_image_button);
    //        settingsButton.setImageDrawable(PDUIColorUtils.getSettingsIcon(getActivity()));
    //        settingsButton.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                startActivity(new Intent(getActivity(), PDUISettingsActivity.class));
    //            }
    //        });
    //
    //        settingsButton.setVisibility(View.GONE);

    mAdapter = new PDUIHomeFlowPagerAdapter(getChildFragmentManager(), getActivity());
    viewPager = (ViewPager) view.findViewById(R.id.pd_home_view_pager);
    viewPager.setOffscreenPageLimit(3);
    viewPager.setAdapter(mAdapter);
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            logTabPageView(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });

    mTabLayout = (BadgedTabLayout) view.findViewById(R.id.pd_home_tab_layout);
    mTabLayout.setupWithViewPager(viewPager);
    PDAPIClient.instance().getCustomer(new PDAPICallback<JsonObject>() {
        @Override
        public void success(JsonObject jsonObject) {
            Log.i("JsonObject", "success: ");
            if (jsonObject.has("customer")) {
                JsonObject customer = jsonObject.getAsJsonObject("customer");
                PDRealmCustomer realmCustomer = PDRealmCustomer.fromJson(customer);

                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                RealmResults<PDRealmCustomer> results = realm.where(PDRealmCustomer.class).findAll();
                results.deleteAllFromRealm();
                realm.copyToRealm(realmCustomer);
                realm.commitTransaction();
                realm.close();
            }
        }

        @Override
        public void failure(int statusCode, Exception e) {
            e.printStackTrace();
        }
    });

    setProfileBadge(0);
    return view;
}

From source file:com.popdeem.sdk.uikit.fragment.PDUIWalletFragment.java

License:Open Source License

private void verifyReward(final int position) {
    final PDReward reward = (PDReward) mRewards.get(position);
    PDAPIClient.instance().verifyInstagramPostForReward(reward.getId(), new PDAPICallback<JsonObject>() {
        @Override//from   www .ja v a2  s  . c  o m
        public void success(JsonObject jsonObject) {
            PDLog.d(PDUIWalletFragment.class, "verify success: " + jsonObject.toString());
            boolean success = false;
            if (jsonObject.has("data")) {
                JsonObject dataObject = jsonObject.getAsJsonObject("data");
                if (dataObject.has("status")) {
                    success = dataObject.get("status").getAsString().equalsIgnoreCase("success");
                }
            }
            if (success) {
                reward.setInstagramVerified(true);
            } else {
                String dialogMessage = String.format(Locale.getDefault(),
                        "Please ensure your Instagram post includes the required hashtag '%1s'. You may edit the post and come back here to verify. Unverified rewards expire in 24 hours.",
                        reward.getInstagramOptions().getForcedTag());
                PDUIDialogUtils.showBasicOKAlertDialog(getActivity(), "Instagram post not verified",
                        dialogMessage);
            }
            reward.setVerifying(false);
            //                mAdapter.notifyItemChanged(position);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void failure(int statusCode, Exception e) {
            PDLog.d(PDUIWalletFragment.class,
                    "verify failed: code=" + statusCode + ", message=" + e.getMessage());
            reward.setVerifying(false);
            //                mAdapter.notifyItemChanged(position);
            mAdapter.notifyDataSetChanged();
            String dialogMessage = String.format(Locale.getDefault(),
                    "Please ensure your Instagram post includes the required hashtag '%1s'. You may edit the post and come back here to verify. Unverified rewards expire in 24 hours.",
                    reward.getInstagramOptions().getForcedTag());
            PDUIDialogUtils.showBasicOKAlertDialog(getActivity(), "Instagram post not verified", dialogMessage);
        }
    });
}

From source file:com.popdeem.sdk.uikit.fragment.PDUIWalletFragment.java

License:Open Source License

private void refreshWallet() {
    //        deleteDirectoryTree(getActivity());
    Log.i("PDUIWalletFragment", "Refreshing Wallet");
    mSwipeRefreshLayout.post(new Runnable() {
        @Override/*ww w.ja va2s.co m*/
        public void run() {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    });

    finishedWallet = false;
    finishedMessages = false;

    final PDRealmUserDetails userDetails = realm.where(PDRealmUserDetails.class).findFirst();
    if (userDetails == null) {
        Log.i("PDUIWalletFragment", "refreshWallet: user is Null, clearing list");
        mRewards.clear();
        mAdapter.notifyDataSetChanged();
        mSwipeRefreshLayout.setRefreshing(false);
        //            mNoItemsInWalletView.setVisibility(mRewards.size() == 0 ? View.VISIBLE : View.GONE);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                Log.i("PDUIWalletFragment", "Removing refresh");
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    } else {
        Log.i("PDUIWalletFragment", "refreshWallet: user exists");
        //            PDAPIClient.instance().getRewardsInWallet(new PDAPICallback<ArrayList<PDReward>>() {

        PDAPIClient.instance().getUserDetailsForId(userDetails.getId(), new PDAPICallback<JsonObject>() {

            @Override
            public void success(JsonObject jsonObject) {
                if (jsonObject.get("status").getAsString().equalsIgnoreCase("User Data")) {
                    JsonObject user = jsonObject.getAsJsonObject("user");
                    float score = Float.valueOf(user.get("advocacy_score").getAsString());

                    realm.beginTransaction();
                    userDetails.setAdvocacyScore(score);
                    realm.commitTransaction();
                    mAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void failure(int statusCode, Exception e) {

            }
        });
        PDAPIClient.instance().getRewardsInWallet(new PDAPICallback<JsonObject>() {
            @Override
            public void success(JsonObject jsonObject) {
                JsonArray jsonArray = jsonObject.getAsJsonArray("rewards");
                ArrayList<PDReward> pdRewards = new ArrayList<PDReward>();
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder.registerTypeAdapter(PDReward.class, new PDRewardDeserializer());

                Gson gson = gsonBuilder.create();

                for (int i = 0; i < jsonArray.size(); i++) {
                    PDReward reward = gson.fromJson(jsonArray.get(i), PDReward.class);
                    pdRewards.add(reward);
                }

                // Sort rewards
                Collections.sort(pdRewards, new PDRewardComparator(PDRewardComparator.CLAIMED_AT_COMPARATOR));

                // If a reward has been revoked, remove it from the users wallet
                int verifyingRewardIndex = -1;
                for (Iterator<PDReward> iterator = pdRewards.iterator(); iterator.hasNext();) {
                    PDReward r = iterator.next();
                    if (r.getRevoked().equalsIgnoreCase("true")) {
                        iterator.remove();
                        continue;
                    }

                    //                        if (mAutoVerifyRewardId != null && r.getId().equalsIgnoreCase(mAutoVerifyRewardId) && !r.isInstagramVerified()) {
                    //                            r.setVerifying(true);
                    //                            verifyingRewardIndex = pdRewards.indexOf(r);
                    //                            mAutoVerifyRewardId = null;
                    //                        }
                }

                JsonArray jsonArrayTiers = jsonObject.getAsJsonArray("tiers");
                ArrayList<PDEvent> pdEvents = new ArrayList<PDEvent>();

                Gson gsonEvents = new Gson();

                for (int i = 0; i < jsonArrayTiers.size(); i++) {
                    PDEvent event = gsonEvents.fromJson(jsonArrayTiers.get(i), PDEvent.class);
                    pdEvents.add(event);
                }

                mRewards.clear();
                mRewards.addAll(pdEvents);
                mRewards.addAll(pdRewards);

                Collections.sort(mRewards, new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        long time1 = 0;
                        long time2 = 0;

                        if (o1 instanceof PDReward) {
                            PDReward reward = (PDReward) o1;
                            time1 = reward.getClaimedAt();
                        } else {
                            PDEvent reward = (PDEvent) o1;
                            time1 = reward.getDate();
                        }

                        if (o2 instanceof PDReward) {
                            PDReward reward = (PDReward) o2;
                            time2 = reward.getClaimedAt();
                        } else {
                            PDEvent reward = (PDEvent) o2;
                            time2 = reward.getDate();
                        }

                        if (time1 < time2)
                            return 1;
                        else if (time1 > time2)
                            return -1;

                        return 0;
                    }

                });

                mAdapter.notifyDataSetChanged();
                finishedWallet = true;
                if (finishedMessages && finishedWallet) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                //                    mNoItemsInWalletView.setVisibility(mRewards.size() == 0 ? View.VISIBLE : View.GONE);

                //                    if (verifyingRewardIndex != -1) {
                //                        verifyReward(verifyingRewardIndex);
                //                    }else{
                //                        PDUIGratitudeDialog.showGratitudeDialog(getActivity(), "share");
                //                    }
            }

            @Override
            public void failure(int statusCode, Exception e) {
                finishedWallet = true;
                if (finishedMessages && finishedWallet) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    PDAPIClient.instance().getPopdeemMessages(new PDAPICallback<ArrayList<PDMessage>>() {
        @Override
        public void success(ArrayList<PDMessage> messages) {
            PDLog.d(PDUIInboxFragment.class, "message count: " + messages.size());
            ArrayList<PDMessage> mMessages = new ArrayList<>();
            mMessages.addAll(messages);
            int unread = 0;
            for (int i = 0; i < messages.size(); i++) {
                if (!messages.get(i).isRead()) {
                    unread++;
                }
            }
            setBadges(unread);

            finishedMessages = true;
            if (finishedMessages && finishedWallet) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }

        @Override
        public void failure(int statusCode, Exception e) {
            finishedMessages = true;
            if (finishedMessages && finishedWallet) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }
    });
}