Java Code Examples for org.json.JSONObject#isNull()

The following examples show how to use org.json.JSONObject#isNull() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: qcloudsms_java   File: SmsMultiSenderResult.java    License: MIT License 6 votes vote down vote up
@Override
public SmsMultiSenderResult parseFromHTTPResponse(HTTPResponse response)
        throws JSONException {

    JSONObject json = parseToJson(response);

    result = json.getInt("result");
    errMsg = json.getString("errmsg");

    if (json.has("ext")) {
        ext = json.getString("ext");
    }
    if (json.has("detail") && !json.isNull("detail")) {
        JSONArray jsonDetail = json.getJSONArray("detail");
        for (int i = 0; i < jsonDetail.length(); i++) {
            details.add((new Detail()).parse(jsonDetail.getJSONObject(i)));
        }
    }


    return this;
}
 
Example 2
Source Project: YiBo   File: SinaCountAdaptor.java    License: Apache License 2.0 6 votes vote down vote up
public static UnreadCount createRemindCount(String jsonString) throws LibException {
	UnreadCount count = null;
	try {
		JSONObject json = new JSONObject(jsonString);
		count = new UnreadCount();
		if (!json.isNull("status")) {
			count.setStatusCount(json.getInt("status"));
		}
		count.setMetionCount(json.getInt("mention_status"));
		count.setCommentCount(json.getInt("cmt"));
		count.setDireceMessageCount(json.getInt("dm"));
		count.setFollowerCount(json.getInt("follower"));
	} catch (JSONException e) {
		throw new LibException(LibResultCode.JSON_PARSE_ERROR);
	}
	return count;
}
 
Example 3
Source Project: m2x-android   File: Distribution.java    License: MIT License 6 votes vote down vote up
@Override
public void fromJson(JSONObject jsonObject) throws JSONException {
    id = jsonObject.optString("id", null);
    name = jsonObject.optString("name", null);
    description = jsonObject.optString("description", null);
    visibility = Visibility.parse(jsonObject.optString("visibility", null));
    status = jsonObject.optString("status", null);
    url = jsonObject.optString("url", null);
    key = jsonObject.optString("key", null);
    try {
        if (!jsonObject.isNull("created"))
            created = DateUtils.stringToDateTime(jsonObject.getString("created"));
        if (!jsonObject.isNull("updated"))
            updated = DateUtils.stringToDateTime(jsonObject.getString("updated"));
    } catch (ParseException e) {
        throw new JSONException(e.getMessage());
    }
    if (!jsonObject.isNull("metadata")) {
        metadata = ArrayUtils.jsonObjectToMap(jsonObject.getJSONObject("metadata"));
    }
    if (!jsonObject.isNull("devices")) {
        devices = Devices.fromJsonObject(jsonObject.getJSONObject("devices"));
    }
}
 
Example 4
public static VideoOnDemand getVod(JSONObject vodObject) throws JSONException {
	final String TITLE_STRING = "title";
	final String VIDEO_ID_STRING = "_id";
	final String GAME_TITLE_STRING = "game";
	final String VIDEO_LENGTH_INT = "length";
	final String VIDEO_VIEWS_INT = "views";
	final String RECORDED_DATE_STRING = "recorded_at";
	final String PREVIEW_URL_OBJECT = "preview";
		final String PREVIEW_URL_SMALL_STRING = "small";
		final String PREVIEW_URL_MEDIUM_STRING = "medium";
		final String PREVIEW_URL_LARGE_STRING = "large";
	final String CHANNEL_OBJECT = "channel";
		final String CHANNEL_NAME_STRING = "name";
		final String CHANNEL_DISPLAY_NAME_STRING = "display_name";

	JSONObject channel = vodObject.getJSONObject(CHANNEL_OBJECT);
	String gameTitle = "";
	if (!vodObject.isNull(GAME_TITLE_STRING)) {
		gameTitle = vodObject.getString(GAME_TITLE_STRING);
	}

	return new VideoOnDemand(vodObject.getString(TITLE_STRING), gameTitle, vodObject.getJSONObject(PREVIEW_URL_OBJECT).getString(PREVIEW_URL_MEDIUM_STRING), vodObject.getString(VIDEO_ID_STRING), channel.getString(CHANNEL_NAME_STRING), channel.getString(CHANNEL_DISPLAY_NAME_STRING), vodObject.getInt(VIDEO_VIEWS_INT), vodObject.getInt(VIDEO_LENGTH_INT), vodObject.has(RECORDED_DATE_STRING) ? vodObject.getString(RECORDED_DATE_STRING) : "");
}
 
Example 5
Source Project: spring-data-cosmosdb   File: PageTestUtils.java    License: MIT License 5 votes vote down vote up
private static boolean continuationTokenIsNull(CosmosPageRequest pageRequest) {
    final String tokenJson = pageRequest.getRequestContinuation();
    if (tokenJson == null) {
        return true;
    }

    final JSONObject jsonObject = new JSONObject(tokenJson);

    return jsonObject.isNull("compositeToken");
}
 
Example 6
Source Project: Aegis   File: VaultFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Header fromJson(JSONObject obj) throws VaultFileException {
    if (obj.isNull("slots") && obj.isNull("params")) {
        return new Header(null, null);
    }

    try {
        SlotList slots = SlotList.fromJson(obj.getJSONArray("slots"));
        CryptParameters params = CryptParameters.fromJson(obj.getJSONObject("params"));
        return new Header(slots, params);
    } catch (SlotListException | JSONException | EncodingException e) {
        throw new VaultFileException(e);
    }
}
 
Example 7
Source Project: product-emm   File: AppListActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
    String responseStatus;
    CommonDialogUtils.stopProgressDialog(progressDialog);
    if (requestCode == Constants.APP_LIST_REQUEST_CODE) {
        if (result != null && result.get(Constants.RESPONSE) != null) {
            responseStatus = result.get(Constants.STATUS);
            if (Constants.Status.SUCCESSFUL.equals(responseStatus)) {
                try {
                    JSONObject payload = new JSONObject(result.get(Constants.RESPONSE));
                    if (!payload.isNull(Constants.ApplicationPayload.APP_LIST)) {
                        JSONArray applicationList = payload.getJSONArray(Constants.ApplicationPayload.APP_LIST);
                        appList.setVisibility(View.VISIBLE);
                        btnMobileApps.setVisibility(View.VISIBLE);
                        btnWebApps.setVisibility(View.VISIBLE);
                        txtError.setVisibility(View.GONE);
                        setAppListUI(applicationList);
                    }
                } catch (JSONException e) {
                    appList.setVisibility(View.GONE);
                    btnMobileApps.setVisibility(View.GONE);
                    btnWebApps.setVisibility(View.GONE);
                    txtError.setVisibility(View.VISIBLE);
                    Log.e(TAG, "Failed parsing application list response" + e);
                }
            } else {
                appList.setVisibility(View.GONE);
                btnMobileApps.setVisibility(View.GONE);
                btnWebApps.setVisibility(View.GONE);
                txtError.setVisibility(View.VISIBLE);
            }
        } else {
            appList.setVisibility(View.GONE);
            btnMobileApps.setVisibility(View.GONE);
            btnWebApps.setVisibility(View.GONE);
            txtError.setVisibility(View.VISIBLE);
        }
    }
}
 
Example 8
Source Project: java-firebase-fcm-client   File: FcmResponse.java    License: MIT License 5 votes vote down vote up
private void parse(JSONObject json) {

		if (!json.isNull("multicast_id")) {
			mMulticastId = (Long) json.getLong("multicast_id");
		}
		if (!json.isNull("success")) {
			mSuccess = (Integer) json.getInt("success");
		}
		if (!json.isNull("failure")) {
			mFailure = (Integer) json.getInt("failure");
		}
		if (!json.isNull("canonical_ids")) {
			mCanonicalIds = (Integer) json.getInt("canonical_ids");
		}

		JSONArray results = (JSONArray) getn(json, "results");

		if (results != null) {
			for (int i = 0; i < results.length(); i++) {

				if (mResultList == null) {
					mResultList = new ArrayList<FcmResult>();
				}

				FcmResult rslt = new FcmResult();
				mResultList.add(rslt);

				JSONObject obj = (JSONObject) results.get(i);
				if (!obj.isNull("message_id")) {
					rslt.messageId = (String) getn(obj, "message_id");
				}
				if (!obj.isNull("error")) {
					rslt.error = (String) getn(obj, "error");
				}
				if (!obj.isNull("registration_id")) {
					rslt.registrationId = (String) getn(obj, "registration_id");
				}
			}
		}
	}
 
Example 9
Source Project: barterli_android   File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the field type for a particular key
 * 
 * @param jsonObject The {@link JSONObject} to check the key
 * @param key The key to check
 * @return what kind of type the field is, represented as a
 *         {@link FieldType} object
 * @throws JSONException If the key is not present, or the value is
 *             <code>null</code>
 */
public static FieldType getTypeForKey(final JSONObject jsonObject,
                final String key) throws JSONException {

    if (jsonObject.isNull(key)) {
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_OBJECT, key));
    }

    final Object object = jsonObject.get(key);

    if (object instanceof Long) {
        return FieldType.LONG;
    } else if (object instanceof Integer) {
        return FieldType.INT;
    } else if (object instanceof Boolean) {
        return FieldType.BOOL;
    } else if (object instanceof String) {
        return FieldType.STRING;
    } else if (object instanceof Double) {
        return FieldType.DOUBLE;
    } else if (object instanceof JSONObject) {
        return FieldType.OBJECT;
    } else if (object instanceof JSONArray) {
        return FieldType.ARRAY;
    }

    throw new JSONException(String.format(Locale.US, UNKNOWN_TYPE, object
                    .getClass().getName()));
}
 
Example 10
Source Project: bither-desktop-java   File: Ticker.java    License: Apache License 2.0 5 votes vote down vote up
private static Ticker formatTicker(JSONObject json, MarketType marketType)
        throws JSONException {
    Ticker ticker = new Ticker();
    if (!json.isNull(VOLUME)) {
        ticker.setAmount(json.getDouble(VOLUME) / Math.pow(10, 8));
    }
    if (!json.isNull(HIGH)) {
        ticker.setHigh(json.getDouble(HIGH) / 100);
    }
    if (!json.isNull(LOW)) {
        ticker.setLow(json.getDouble(LOW) / 100);
    }
    if (!json.isNull(LAST)) {
        ticker.setNew(json.getDouble(LAST) / 100);
    }
    if (!json.isNull(BID)) {
        ticker.setBuy(json.getDouble(BID) / 100);
    }
    if (!json.isNull(ASK)) {
        ticker.setSell(json.getDouble(ASK) / 100);
    }

    ticker.setAmp(-1);
    ticker.setTotal(-1);
    ticker.setLevel(-1);
    ticker.setOpen(-1);
    ticker.setMarketType(marketType);
    return ticker;

}
 
Example 11
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void blockUninstallByPackageName(Operation operation) throws AndroidAgentException {
    String packageName = null;
    try {
        JSONObject hideAppData = new JSONObject(operation.getPayLoad().toString());
        if (!hideAppData.isNull(getContextResources().getString(R.string.intent_extra_package))) {
            packageName = (String) hideAppData.get(getContextResources().getString(R.string.intent_extra_package));
        }

        operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
        getResultBuilder().build(operation);

        if (packageName != null && !packageName.isEmpty()) {
            getDevicePolicyManager().setUninstallBlocked(getCdmDeviceAdmin(), packageName, true);
        }

        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "App-Uninstall-Block successful.");
        }
    } catch (JSONException e) {
        operation.setStatus(getContextResources().getString(R.string.operation_value_error));
        operation.setOperationResponse("Error in parsing APP_BLOCK payload.");
        getResultBuilder().build(operation);
        throw new AndroidAgentException("Invalid JSON format.", e);
    }
}
 
Example 12
@Override
public ArrayList<CommentNumber> parse(Response response) {

    if (!response.isSuccessful())
        return null;

    try {
        String body = response.body().string();
        JSONObject jsonObject = new JSONObject(body).getJSONObject("response");
        String[] comment_IDs = response.request().url().toString().split("\\=")[1].split("\\,");
        ArrayList<CommentNumber> commentNumbers = new ArrayList<>();

        GsonHelper<CommentNumber> helper = new GsonHelper<>();

        for (String comment_ID : comment_IDs) {
            if (!jsonObject.isNull(comment_ID)) {
                JSONObject commentObject = jsonObject.getJSONObject(comment_ID);
                CommentNumber commentNumber = helper.fromJson(commentObject.toString(), CommentNumber.class);
                commentNumbers.add(commentNumber);
            } else {
                //可能会出现没有对应id的数据的情况,为了保证条数一致,添加默认数据
                commentNumbers.add(new CommentNumber("0", "0", 0));
            }
        }
        return commentNumbers;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 13
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void hideApp(Operation operation) throws AndroidAgentException {
    String packageName = null;
    try {
        JSONObject hideAppData = new JSONObject(operation.getPayLoad().toString());
        if (!hideAppData.isNull(getContextResources().getString(R.string.intent_extra_package))) {
            packageName = (String) hideAppData.get(getContextResources().getString(R.string.intent_extra_package));
        }

        operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
        getResultBuilder().build(operation);

        if (packageName != null && !packageName.isEmpty()) {
            getDevicePolicyManager().setApplicationHidden(getCdmDeviceAdmin(), packageName, true);
        }

        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "App-Hide successful.");
        }
    } catch (JSONException e) {
        operation.setStatus(getContextResources().getString(R.string.operation_value_error));
        operation.setOperationResponse("Error in parsing APP_HIDE payload.");
        getResultBuilder().build(operation);
        throw new AndroidAgentException("Invalid JSON format.", e);
    }
}
 
Example 14
Source Project: product-emm   File: AlertActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method starts a VPN connection.
 */
private void startVpn() {

	try {
		JSONObject vpnData = new JSONObject(payload);
		if (!vpnData.isNull(resources.getString(R.string.intent_extra_server))) {
			serverAddress = (String) vpnData.get(resources.getString(R.string.intent_extra_server));
		}
		if (!vpnData.isNull(resources.getString(R.string.intent_extra_server_port))) {
			serverPort = (String) vpnData.get(resources.getString(R.string.intent_extra_server_port));
		}

		if (!vpnData.isNull(resources.getString(R.string.intent_extra_shared_secret))) {
			sharedSecret = (String) vpnData.get(resources.getString(R.string.intent_extra_shared_secret));
		}

		if (!vpnData.isNull(resources.getString(R.string.intent_extra_dns))) {
			dnsServer = (String) vpnData.get(resources.getString(R.string.intent_extra_dns));
		}
	} catch (JSONException e) {
		Log.e(TAG, "Invalid VPN payload " + e);
	}

	Intent intent = VpnService.prepare(this);
	if (intent != null) {
		startActivityForResult(intent, VPN_REQUEST_CODE);
	} else {
		onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
	}
}
 
Example 15
private boolean onActionFlag(Context context, EntityMessage message, JSONObject jargs) throws JSONException {
    Integer color = (jargs.has("color") && !jargs.isNull("color")
            ? jargs.getInt("color") : null);

    EntityOperation.queue(context, message, EntityOperation.FLAG, true, color);

    message.ui_flagged = true;
    message.color = color;

    return true;
}
 
Example 16
private void writeToDataFeed(String message) {
     try{
     	JSONObject msgJson  = new JSONObject(message);
         TwitterDataFeed dataFeed = new TwitterDataFeed();
         dataFeed.setCode(collectionCode);
         dataFeed.setFeed(msgJson);
         JSONObject aidrJson = msgJson.getJSONObject("aidr");
dataFeed.setAidr(aidrJson);
dataFeed.setSource(aidrJson.getString("doctype"));
if(msgJson.has("coordinates") && !msgJson.isNull("coordinates")){
	dataFeed.setGeo(msgJson.getJSONObject("coordinates"));
}
if(msgJson.has("place") && !msgJson.isNull("place")){
	dataFeed.setPlace(msgJson.getJSONObject("place"));
}

         Long dataFeedId = dataFeedService.persist(dataFeed);
         if(dataFeedId != null && saveMediaEnabled) {
         	JSONObject entities = msgJson.getJSONObject("entities");
         	if(entities != null && entities.has("media")
         			&& entities.getJSONArray("media") != null
         			&& entities.getJSONArray("media").length() > 0 
         			&& entities.getJSONArray("media").getJSONObject(0).getString("type") != null
         			&& entities.getJSONArray("media").getJSONObject(0).getString("type").equals("photo")) {
         		String imageUrl = entities.getJSONArray("media").getJSONObject(0).getString("media_url");
         		imageFeedService.checkAndSaveIfNotExists(dataFeedId, collectionCode, imageUrl);
         	}
         }
     }catch(Exception e){
     	logger.error("Error in persisting :::: " + message);
     	logger.error("Exception while persisting to postgres db ", e );
     }
 }
 
Example 17
Source Project: Cangol-appcore   File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getObject(JSONObject obj, String key) {
    try {
        if (obj.isNull(key)) {
            return null;
        } else {
            return obj.get(key);
        }
    } catch (JSONException e) {
        return null;
    }
}
 
Example 18
Source Project: nbp   File: RestClient.java    License: Apache License 2.0 4 votes vote down vote up
private boolean isFailed(JSONObject response) throws Exception {
    if(!response.has("code") || response.isNull("code"))
        return false;
    return true;
}
 
Example 19
public static EntityIdentity fromJSON(JSONObject json) throws JSONException {
    EntityIdentity identity = new EntityIdentity();
    identity.id = json.getLong("id");
    identity.name = json.getString("name");
    identity.email = json.getString("email");
    if (json.has("display") && !json.isNull("display"))
        identity.display = json.getString("display");
    if (json.has("color"))
        identity.color = json.getInt("color");
    if (json.has("signature") && !json.isNull("signature"))
        identity.signature = json.getString("signature");

    identity.host = json.getString("host");
    identity.starttls = json.getBoolean("starttls");
    identity.insecure = (json.has("insecure") && json.getBoolean("insecure"));
    identity.port = json.getInt("port");
    identity.auth_type = json.getInt("auth_type");
    if (json.has("provider"))
        identity.provider = json.getString("provider");
    identity.user = json.getString("user");
    identity.password = json.getString("password");
    if (json.has("certificate_alias"))
        identity.certificate_alias = json.getString("certificate_alias");
    if (json.has("realm") && !json.isNull("realm"))
        identity.realm = json.getString("realm");
    if (json.has("fingerprint"))
        identity.fingerprint = json.getString("fingerprint");
    if (json.has("use_ip"))
        identity.use_ip = json.getBoolean("use_ip");
    if (json.has("ehlo"))
        identity.ehlo = json.getString("ehlo");

    identity.synchronize = json.getBoolean("synchronize");
    identity.primary = json.getBoolean("primary");
    if (json.has("sender_extra"))
        identity.sender_extra = json.getBoolean("sender_extra");
    if (json.has("sender_extra_regex"))
        identity.sender_extra_regex = json.getString("sender_extra_regex");

    if (json.has("replyto") && !json.isNull("replyto"))
        identity.replyto = json.getString("replyto");
    if (json.has("cc") && !json.isNull("cc"))
        identity.cc = json.getString("cc");
    if (json.has("bcc") && !json.isNull("bcc"))
        identity.bcc = json.getString("bcc");

    return identity;
}
 
Example 20
Source Project: android-discourse   File: BaseModel.java    License: Apache License 2.0 4 votes vote down vote up
protected String getString(JSONObject object, String key) throws JSONException {
    return object.isNull(key) ? null : Html.fromHtml(object.getString(key)).toString().trim();
}