Java Code Examples for org.json.JSONArray#optString()

The following examples show how to use org.json.JSONArray#optString() . 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 File: NotificationHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void handleChannelData(final String action, final JSONArray payload) throws BitfinexClientException {
    logger.debug("Got notification callback {}", payload.toString());

    if (payload.isEmpty()) {
        return;
    }

    // Test for order error callback
    // [0,"n",[null,"on-req",null,null,[null,null,1513970684865000,"tBTCUSD",null,null,0.001,0.001,"EXCHANGE MARKET",null,null,null,null,null,null,null,12940,null,null,null,null,null,null,0,null,null],null,"ERROR","Invalid order: minimum size for BTC/USD is 0.002"]]
    if ("on-req".equals(payload.getString(1))) {
        final String state = payload.optString(6);
        if ("ERROR".equals(state)) {
            BitfinexSubmittedOrder exchangeOrder = jsonToBitfinexSubmittedOrder(payload);
            submittedOrderConsumer.accept(symbol, exchangeOrder);
        }
    }
}
 
Example 2
Source File: JsonParser.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a List of Strings from the JSON object with the given name.
 * The referenced property must be a {@link JSONArray}. The values of the array will be
 * converted to Strings.
 *
 * @param propName The name of the JSON array property
 * @return The List of String values for the property with the given name
 * @throws InvalidJsonDocumentException When the property is missing or the array is empty
 */
@NonNull
public List<String> getRequiredStringArray(String propName)
        throws InvalidJsonDocumentException {
    JSONArray stringsJsonArray = mJson.optJSONArray(propName);
    if (stringsJsonArray == null || stringsJsonArray.length() == 0) {
        throw new InvalidJsonDocumentException(
                propName + " is required but not specified in the document");
    }

    List<String> scopes = new LinkedList<>();
    for (int i = 0; i < stringsJsonArray.length(); ++i) {
        String value = stringsJsonArray.optString(i);
        if (TextUtils.isEmpty(value)) {
            throw new InvalidJsonDocumentException(
                    propName + " must have an array of Strings");
        }
        scopes.add(value);
    }

    return scopes;
}
 
Example 3
Source File: CustomFields.java    From JianDanRxJava with Apache License 2.0 6 votes vote down vote up
public static CustomFields parseCache(final JSONObject jsonObject) {
    CustomFields customFields;
    if (jsonObject == null) {
        customFields = null;
    } else {
        customFields = new CustomFields();
        final JSONArray optJSONArray = jsonObject.optJSONArray("thumb_c");
        if (optJSONArray != null && optJSONArray.length() > 0) {
            customFields.thumb_c = optJSONArray.optString(0);
            if (customFields.thumb_c.contains("custom")) {
                customFields.thumb_m = customFields.thumb_c.replace("custom", "medium");
            }
        }
        final JSONArray optJSONArray2 = jsonObject.optJSONArray("views");
        if (optJSONArray2 != null && optJSONArray2.length() > 0) {
            customFields.views = optJSONArray2.optString(0);
        }
    }
    return customFields;
}
 
Example 4
Source File: FacebookContactMatcher.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
private void matchContacts(final Context context, final GraphUser user, 
		Response response, final ModelCallback<JSONArray> callback) {
	JSONArray friends = response.getGraphObject()
			.getInnerJSONObject().optJSONArray("data");
	JSONArray friendsHashes = new JSONArray();
	for (int i = 0; i < friends.length(); i++) {
		String friendId = friends.optString(i, "id");
		String friendHash = ContactMatcherUtils.hash(NAME, friendId);
		friendsHashes.put(friendHash);
	}
	
	JSONArray myHashes = new JSONArray();
	myHashes.put(user.getId());
	
	ContactMatcherUtils.reportToFriendFinder(context, callback, 
			friendsHashes, myHashes);
}
 
Example 5
Source File: AbstractQuery.java    From algoliasearch-client-android with MIT License 6 votes vote down vote up
@Nullable protected static String[] parseArray(@Nullable String string) {
    if (string == null) {
        return null;
    }
    // First try to parse JSON notation.
    try {
        JSONArray array = new JSONArray(string);
        String[] result = new String[array.length()];
        for (int i = 0; i < result.length; ++i) {
            result[i] = array.optString(i);
        }
        return result;
    }
    // Otherwise parse as a comma-separated list.
    catch (JSONException e) {
        return string.split(",");
    }
}
 
Example 6
Source File: LivePhoto.java    From sealrtc-android with MIT License 6 votes vote down vote up
public String[] getStickerImagePaths() {
    if (this.stickerImagePathStr != null) {
        try {
            JSONArray jsonArray = new JSONArray(this.stickerImagePathStr);
            int length = jsonArray.length();
            String[] images = new String[length];
            for (int i = 0; i < length; i++) {
                images[i] = jsonArray.optString(i);
            }
            return images;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 7
Source File: CustomFields.java    From JianDan_OkHttpWithVolley with Apache License 2.0 6 votes vote down vote up
public static CustomFields parse(final JSONObject jsonObject) {
    CustomFields customFields;
    if (jsonObject == null) {
        customFields = null;
    } else {
        customFields = new CustomFields();
        final JSONArray optJSONArray = jsonObject.optJSONArray("thumb_c");
        if (optJSONArray != null && optJSONArray.length() > 0) {
            customFields.thumb_c = optJSONArray.optString(0);
            if (customFields.thumb_c.contains("custom")) {
                customFields.thumb_m = customFields.thumb_c.replace("custom", "medium");
            }
        }
        final JSONArray optJSONArray2 = jsonObject.optJSONArray("views");
        if (optJSONArray2 != null && optJSONArray2.length() > 0) {
            customFields.views = optJSONArray2.optString(0);
        }
    }
    return customFields;
}
 
Example 8
Source File: CamFlow.java    From SPADE with GNU General Public License v3.0 6 votes vote down vote up
/**
 * The json object must contain a key 'annotations' whose value is a json object
 * 
 * @param object json object either a vertex or an edge
 * @return either empty or filled map
 * @throws Throwable malformed exception
 */
private Map<String, String> getAnnotationsFromJSON(JSONObject object) throws Throwable{
	Map<String, String> annotations = new HashMap<String, String>();
	JSONObject annotationsObject = object.optJSONObject(JSON_KEY_ANNOTATIONS);
	if(annotationsObject == null){
		throw new MalformedCamFlowObjectException("NULL '"+JSON_KEY_ANNOTATIONS+"'");
	}
	if(annotationsObject != null && annotationsObject.length() > 0){
		JSONArray namesArray = annotationsObject.names();
		for(int i = 0; i < annotationsObject.length(); i++){
			String key = namesArray.optString(i, null);
			if(key != null){
				String value = annotationsObject.optString(key, null);
				annotations.put(key, value);
			}else{
				throw new MalformedCamFlowObjectException("NULL key at index: " + i);
			}
		}
	}
	return annotations;
}
 
Example 9
Source File: TMReminderTagsView.java    From Virtualview-Android with MIT License 5 votes vote down vote up
public void setTags(JSONArray tags) {
    if (tags != null) {
        int length = tags.length();
        String[] newTags = new String[length];
        for (int i = 0; i < length; i++) {
            newTags[i] = tags.optString(i);
        }
        setTags(newTags);
    }

}
 
Example 10
Source File: HybridBridge.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
private void registerSuperProperty(Context context, JSONArray array) {
    if (context != null) {
        if (array != null && array.length() > 0) {
            String key = array.optString(0);
            Object value = array.opt(1);
            AgentProcess.getInstance().registerJsSuperProperty(key,value);
        }
    }
}
 
Example 11
Source File: WizPurchase.java    From cordova-plugin-wizpurchase with MIT License 5 votes vote down vote up
/**
 * Make the Product Purchase
 *
 * @param args Product Id to be purchased and DeveloperPayload
 * @param callbackContext Instance
 **/
private void makePurchase(JSONArray args, CallbackContext callbackContext) throws JSONException {
	// Retain the callback and wait
	mMakePurchaseCbContext = callbackContext;
	retainCallBack(mMakePurchaseCbContext);
	// Instance the given product Id to be purchase
	final String productId = args.getString(0);
	// Update the DeveloperPayload with the given value. empty if not passed
	mDevPayload = args.optString(1);

	// Check if the Inventory is available
	if (mInventory != null) {
		// Set up the activity result callback to this class
		cordova.setActivityResultCallback(this);
		cordova.getThreadPool().execute(new Runnable() {
			public void run() {
				// Buy the product
				buy(productId);
			}
		});
	} else {
		// Initialise the Plug-In adding the product to be purchased
		cordova.getThreadPool().execute(new Runnable() {
			public void run() {
				List<String> skus = new ArrayList<String>();
				skus.add(0, productId);
				init(skus);
			}
		});
	}
}
 
Example 12
Source File: FileTransfer.java    From reacteu-app with MIT License 5 votes vote down vote up
/**
 * Convenience method to read a parameter from the list of JSON args.
 * @param args                      the args passed to the Plugin
 * @param position          the position to retrieve the arg from
 * @param defaultString the default to be used if the arg does not exist
 * @return String with the retrieved value
 */
private static String getArgument(JSONArray args, int position, String defaultString) {
    String arg = defaultString;
    if (args.length() > position) {
        arg = args.optString(position);
        if (arg == null || "null".equals(arg)) {
            arg = defaultString;
        }
    }
    return arg;
}
 
Example 13
Source File: FileTransfer.java    From reader with MIT License 5 votes vote down vote up
/**
 * Convenience method to read a parameter from the list of JSON args.
 * @param args                      the args passed to the Plugin
 * @param position          the position to retrieve the arg from
 * @param defaultString the default to be used if the arg does not exist
 * @return String with the retrieved value
 */
private static String getArgument(JSONArray args, int position, String defaultString) {
    String arg = defaultString;
    if (args.length() > position) {
        arg = args.optString(position);
        if (arg == null || "null".equals(arg)) {
            arg = defaultString;
        }
    }
    return arg;
}
 
Example 14
Source File: FileTransfer.java    From reacteu-app with MIT License 5 votes vote down vote up
/**
 * Convenience method to read a parameter from the list of JSON args.
 * @param args                      the args passed to the Plugin
 * @param position          the position to retrieve the arg from
 * @param defaultString the default to be used if the arg does not exist
 * @return String with the retrieved value
 */
private static String getArgument(JSONArray args, int position, String defaultString) {
    String arg = defaultString;
    if (args.length() > position) {
        arg = args.optString(position);
        if (arg == null || "null".equals(arg)) {
            arg = defaultString;
        }
    }
    return arg;
}
 
Example 15
Source File: FileTransfer.java    From reader with MIT License 5 votes vote down vote up
/**
 * Convenience method to read a parameter from the list of JSON args.
 * @param args                      the args passed to the Plugin
 * @param position          the position to retrieve the arg from
 * @param defaultString the default to be used if the arg does not exist
 * @return String with the retrieved value
 */
private static String getArgument(JSONArray args, int position, String defaultString) {
    String arg = defaultString;
    if (args.length() > position) {
        arg = args.optString(position);
        if (arg == null || "null".equals(arg)) {
            arg = defaultString;
        }
    }
    return arg;
}
 
Example 16
Source File: VpnConfigGenerator.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
private void ovpnGatewayConfigApi3(StringBuilder stringBuilder, String ipAddress, JSONArray transports) throws JSONException {
    String port;
    String protocol;
    JSONObject openvpnTransport = getTransport(transports, OPENVPN);
    JSONArray ports = openvpnTransport.getJSONArray(PORTS);
    for (int j = 0; j < ports.length(); j++) {
        port = ports.getString(j);
        JSONArray protocols = openvpnTransport.getJSONArray(PROTOCOLS);
        for (int k = 0; k < protocols.length(); k++) {
            protocol = protocols.optString(k);
            String newRemote = REMOTE + " " + ipAddress + " " + port + " " + protocol + newLine;
            stringBuilder.append(newRemote);
        }
    }
}
 
Example 17
Source File: JournalQueryService.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
private List<JSONObject> getTeamMembers(final JSONObject archive, final String teamName) {
    try {
        final JSONArray teams = new JSONArray(archive.optString(Archive.ARCHIVE_TEAMS));

        final List<JSONObject> ret = new ArrayList<JSONObject>();

        for (int i = 0; i < teams.length(); i++) {
            final JSONObject team = teams.optJSONObject(i);
            final String name = team.optString(Common.TEAM_NAME);

            if (name.equals(teamName)) {
                final JSONArray members = team.optJSONArray(User.USERS);

                for (int j = 0; j < members.length(); j++) {
                    final JSONObject member = new JSONObject();
                    final String userId = members.optString(j);
                    member.put(Keys.OBJECT_ID, userId);

                    final JSONObject u = userRepository.get(userId);
                    member.put(User.USER_NAME, u.optString(User.USER_NAME));
                    member.put(UserExt.USER_AVATAR_URL, u.optString(UserExt.USER_AVATAR_URL));
                    member.put(UserExt.USER_UPDATE_TIME, u.opt(UserExt.USER_UPDATE_TIME));
                    member.put(UserExt.USER_REAL_NAME, u.optString(UserExt.USER_REAL_NAME));

                    ret.add(member);
                }

                return ret;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets team members with archive[ " + archive + "] failed", archive);
    }

    return null;
}
 
Example 18
Source File: VpnConfigGenerator.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
private void gatewayConfigApiv1(StringBuilder stringBuilder, String ipAddress, JSONObject capabilities) throws JSONException {
    int port;
    String protocol;
    JSONArray ports = capabilities.getJSONArray(PORTS);
    for (int i = 0; i < ports.length(); i++) {
        port = ports.getInt(i);
        JSONArray protocols = capabilities.getJSONArray(PROTOCOLS);
        for (int j = 0; j < protocols.length(); j++) {
            protocol = protocols.optString(j);
            String newRemote = REMOTE + " " + ipAddress + " " + port + " " + protocol + newLine;
            stringBuilder.append(newRemote);
        }
    }
}
 
Example 19
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected String getString(JSONArray array, int index) {
    return array.optString(index, "");
}
 
Example 20
Source File: JsCallJava.java    From AgentWeb with Apache License 2.0 4 votes vote down vote up
public String call(WebView webView, JSONObject jsonObject) {
    long time = 0;
    if (LogUtils.isDebug()) {
        time = android.os.SystemClock.uptimeMillis();
    }
    if (jsonObject != null) {
        try {
            String methodName = jsonObject.getString(KEY_METHOD);
            JSONArray argsTypes = jsonObject.getJSONArray(KEY_TYPES);
            JSONArray argsVals = jsonObject.getJSONArray(KEY_ARGS);
            String sign = methodName;
            int len = argsTypes.length();
            Object[] values = new Object[len];
            int numIndex = 0;
            String currType;

            for (int k = 0; k < len; k++) {
                currType = argsTypes.optString(k);
                if ("string".equals(currType)) {
                    sign += "_S";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getString(k);
                } else if ("number".equals(currType)) {
                    sign += "_N";
                    numIndex = numIndex * 10 + k + 1;
                } else if ("boolean".equals(currType)) {
                    sign += "_B";
                    values[k] = argsVals.getBoolean(k);
                } else if ("object".equals(currType)) {
                    sign += "_O";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getJSONObject(k);
                } else if ("function".equals(currType)) {
                    sign += "_F";
                    values[k] = new JsCallback(webView, mInterfacedName, argsVals.getInt(k));
                } else {
                    sign += "_P";
                }
            }

            Method currMethod = mMethodsMap.get(sign);

            // 方法匹配失败
            if (currMethod == null) {
                return getReturn(jsonObject, 500, "not found method(" + sign + ") with valid parameters", time);
            }
            // 数字类型细分匹配
            if (numIndex > 0) {
                Class[] methodTypes = currMethod.getParameterTypes();
                int currIndex;
                Class currCls;
                while (numIndex > 0) {
                    currIndex = numIndex - numIndex / 10 * 10 - 1;
                    currCls = methodTypes[currIndex];
                    if (currCls == int.class) {
                        values[currIndex] = argsVals.getInt(currIndex);
                    } else if (currCls == long.class) {
                        //WARN: argsJson.getLong(k + defValue) will return a bigger incorrect number
                        values[currIndex] = Long.parseLong(argsVals.getString(currIndex));
                    } else {
                        values[currIndex] = argsVals.getDouble(currIndex);
                    }
                    numIndex /= 10;
                }
            }

            return getReturn(jsonObject, 200, currMethod.invoke(mInterfaceObj, values), time);
        } catch (Exception e) {
            LogUtils.safeCheckCrash(TAG, "call", e);
            //优先返回详细的错误信息
            if (e.getCause() != null) {
                return getReturn(jsonObject, 500, "method execute result:" + e.getCause().getMessage(), time);
            }
            return getReturn(jsonObject, 500, "method execute result:" + e.getMessage(), time);
        }
    } else {
        return getReturn(jsonObject, 500, "call data empty", time);
    }
}