Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:com.clover.sdk.v3.JsonHelper.java

public static Map<String, Object> getMap(JSONObject object, String key) {
    return toMap(object.optJSONObject(key));
}

From source file:com.company.project.core.connector.JSONHelper.java

/**
 * This method parses an JSON Array out of a collection of JSON Objects
 * within a string.//from w  ww .  j a  v  a 2 s .c  o m
 * 
 * @param jSonData
 *            The JSON String that holds the collection.
 * @return An JSON Array that would contains all the collection object.
 * @throws Exception
 */
public static JSONArray fetchDirectoryObjectJSONArray(JSONObject jsonObject) throws Exception {
    JSONArray jsonArray = new JSONArray();
    jsonArray = jsonObject.optJSONObject("responseMsg").optJSONArray("value");
    return jsonArray;
}

From source file:com.company.project.core.connector.JSONHelper.java

/**
 * This method parses an JSON Object out of a collection of JSON Objects
 * within a string//from w  w w.j a  va2s .  c  o m
 * 
 * @param jsonObject
 * @return An JSON Object that would contains the DirectoryObject.
 * @throws Exception
 */
public static JSONObject fetchDirectoryObjectJSONObject(JSONObject jsonObject) throws Exception {
    JSONObject jObj = new JSONObject();
    jObj = jsonObject.optJSONObject("responseMsg");
    return jObj;
}

From source file:com.company.project.core.connector.JSONHelper.java

/**
 * This method parses the skip token from a json formatted string.
 * //from w  w  w .j a  v a 2 s.  c  o  m
 * @param jsonData
 *            The JSON Formatted String.
 * @return The skipToken.
 * @throws Exception
 */
public static String fetchNextSkiptoken(JSONObject jsonObject) throws Exception {
    String skipToken = "";
    // Parse the skip token out of the string.
    skipToken = jsonObject.optJSONObject("responseMsg").optString("odata.nextLink");

    if (!skipToken.equalsIgnoreCase("")) {
        // Remove the unnecessary prefix from the skip token.
        int index = skipToken.indexOf("$skiptoken=") + (new String("$skiptoken=")).length();
        skipToken = skipToken.substring(index);
    }
    return skipToken;
}

From source file:com.company.project.core.connector.JSONHelper.java

/**
 * @param jsonObject/* w  w  w .j  a  v  a2s  .  com*/
 * @return
 * @throws Exception
 */
public static String fetchDeltaLink(JSONObject jsonObject) throws Exception {
    String deltaLink = "";
    // Parse the skip token out of the string.
    deltaLink = jsonObject.optJSONObject("responseMsg").optString("aad.deltaLink");
    if (deltaLink == null || deltaLink.length() == 0) {
        deltaLink = jsonObject.optJSONObject("responseMsg").optString("aad.nextLink");
        logger.info("deltaLink empty, nextLink ->" + deltaLink);

    }
    if (!deltaLink.equalsIgnoreCase("")) {
        // Remove the unnecessary prefix from the skip token.
        int index = deltaLink.indexOf("deltaLink=") + (new String("deltaLink=")).length();
        deltaLink = deltaLink.substring(index);
    }
    return deltaLink;
}

From source file:info.axbase.app.VersionInfo.java

public static VersionInfo parse(String text) throws JSONException {
    JSONTokener jsonParser = new JSONTokener(text);
    JSONObject msg = (JSONObject) jsonParser.nextValue();
    if (msg == null) {
        return null;
    }//from   w  w w. j  a v a  2s. co m
    if (msg.optInt("error") == 0) {
        JSONObject data = msg.optJSONObject("data");
        if (data == null) {
            return null;
        }

        VersionInfo versionInfo = new VersionInfo();
        versionInfo.fileName = data.optString("fileName");
        versionInfo.whatsNew = data.optString("whatsNew");
        versionInfo.fileTime = data.optLong("fileTime");
        versionInfo.fileSize = data.optLong("fileSize");
        versionInfo.appProject = data.optString("appProject");
        versionInfo.digest = data.optString("digest");
        versionInfo.version = data.optString("version");
        return versionInfo;
    } else {
        Log.e("ParseError", msg.optString("msg"));
        return null;
    }
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules:/*from  w  w w. jav  a  2s. com*/
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:org.eclipse.orion.server.cf.handlers.v1.RoutesHandlerV1.java

@Override
protected CFJob handlePut(Route route, HttpServletRequest request, HttpServletResponse response,
        final String path) {
    final JSONObject jsonData = extractJSONData(request);

    final JSONObject targetJSON = jsonData.optJSONObject(CFProtocolConstants.KEY_TARGET);
    final String domainName = jsonData.optString(CFProtocolConstants.KEY_DOMAIN_NAME, null);
    final String hostName = jsonData.optString(CFProtocolConstants.KEY_HOST, null);

    return new CFJob(request, false) {
        @Override/*w ww .  j a va 2 s.  c  om*/
        protected IStatus performJob() {
            try {
                ComputeTargetCommand computeTargetCommand = new ComputeTargetCommand(this.userId, targetJSON);
                computeTargetCommand.doIt();
                Target target = computeTargetCommand.getTarget();
                if (target == null) {
                    return HttpUtil.createErrorStatus(IStatus.WARNING, "CF-TargetNotSet", "Target not set");
                }

                GetDomainsCommand getDomainsCommand = new GetDomainsCommand(target, domainName);
                IStatus getDomainsStatus = getDomainsCommand.doIt();
                if (!getDomainsStatus.isOK())
                    return getDomainsStatus;

                CreateRouteCommand createRouteCommand = new CreateRouteCommand(target,
                        getDomainsCommand.getDomains().get(0), hostName);
                IStatus createRouteStatus = createRouteCommand.doIt();
                if (!createRouteStatus.isOK())
                    return createRouteStatus;

                return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK,
                        createRouteCommand.getRoute().toJSON());
            } catch (Exception e) {
                String msg = NLS.bind("Failed to handle request for {0}", path); //$NON-NLS-1$
                ServerStatus status = new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                logger.error(msg, e);
                return status;
            }
        }
    };
}

From source file:fr.haploid.webservices.WebServicesTask.java

public WebServicesTask(CobaltFragment fragment, JSONObject call) {
    mFragment = fragment;/*from   w w w. j  a  v  a 2s.  c  om*/
    mCall = call;

    try {
        mCallId = call.getLong(kJSCallId);
        JSONObject data = call.getJSONObject(Cobalt.kJSData);
        mSendCacheResult = data.optBoolean(kJSSendCacheResult);
        mUrl = data.optString(kJSUrl, null);

        if (mUrl != null) {
            mHeaders = data.optJSONObject(kJSHeaders);
            mParams = data.optString(kJSParams);
            mTimeout = data.optInt(kJSTimeout, -1);
            mType = data.getString(kJSType);
            mSaveToStorage = data.optBoolean(kJSSaveToStorage);
        }

        if (mSendCacheResult || mUrl != null)
            mProcessData = data.optJSONObject(kJSProcessData);

        if (mSendCacheResult || (mUrl != null && mSaveToStorage)) {
            mStorageKey = data.getString(kJSStorageKey);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG) {
            Log.e(WebServicesPlugin.TAG, TAG + ": check your Webservice call. Known issues: \n"
                    + "\t- missing data field, \n" + "\t- url field is defined but but missing type field, \n"
                    + "\t- sendCacheResult field is true or url field is defined and saveToStorage field is true but missing storageKey field.\n");
            exception.printStackTrace();
        }
    }
}

From source file:com.jsonstore.api.JSONStoreAddOptions.java

public JSONStoreAddOptions(JSONObject json) {
    this();/*from  w w w  . j a  v a  2s  .c  om*/
    if (json != null) {
        additionalSearchFields = json.optJSONObject(OPTION_ADDITIONAL_SEARCH_FIELDS);
        markDirty = json.optBoolean(OPTION_IS_ADD, false);
    }
}