Example usage for org.json JSONObject NULL

List of usage examples for org.json JSONObject NULL

Introduction

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

Prototype

Object NULL

To view the source code for org.json JSONObject NULL.

Click Source Link

Document

It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.

Usage

From source file:sh.calaba.driver.client.model.impl.RemoteObject.java

protected Object get(WebDriverLikeCommand command, JSONObject payload) {
    Path p = new Path(command).withSession(getSessionId());

    WebDriverLikeRequest request = new WebDriverLikeRequest(command.method(), p, payload);
    WebDriverLikeResponse response = execute(request);
    if (response == null || response.getValue() == JSONObject.NULL) {
        return null;
    } else {//  w  w  w  .ja  v a 2s. c o  m
        return response.getValue();
    }
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given an object extracted from JSONObject field, convert it to an
 * appropriate object with type appropriate for given type so that it can be
 * assigned to the associated field of the ummarshalled object. eg.
 * JSONObject value from a JSONObject field probably needs to be
 * unmarshalled to a class instance. Double from JSONObject may need to be
 * converted to Float. etc./*www  .  j a v  a 2  s.  c om*/
 *
 * @param val Value extracted from JSONObject field.
 * @param genericType Type to convert to. Must be generic type. ie. From
 *                    field.getGenericType().
 * @return Object of the given type so it can be assinged to field with
 * field.set().
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
private static Object valToType(Object val, Type genericType) {
    Object result = null;
    boolean isArray = false;

    Class<?> rawType = null;
    if (genericType instanceof ParameterizedType) {
        rawType = (Class<?>) ((ParameterizedType) genericType).getRawType();
    } else if (genericType instanceof GenericArrayType) {
        rawType = List.class;
        isArray = true;
    } else {
        rawType = (Class<?>) genericType;
    }

    isArray = isArray || rawType.isArray();

    if (val != null && val != JSONObject.NULL) {
        if (rawType.isAssignableFrom(String.class)) {
            if (val instanceof String) {
                result = val;
            } else {
                throw new TypeMismatchException(rawType, val.getClass());
            }
        } else if (isPrimitive(rawType)) {
            result = convertToPrimitiveFieldObj(val, rawType);
        } else if (isArray || rawType.isAssignableFrom(List.class)) {
            if (val instanceof JSONArray) {
                Type itemType = getListItemType(genericType);
                result = JSONToList((JSONArray) val, itemType);

                if (isArray) {
                    List<?> list = (List<?>) result;

                    Class<?> itemClass = null;
                    if (itemType instanceof ParameterizedType) {
                        itemClass = (Class<?>) ((ParameterizedType) itemType).getRawType();
                    } else {
                        itemClass = (Class<?>) itemType;
                    }

                    result = Array.newInstance(itemClass, list.size());
                    int cnt = 0;
                    for (Object i : list) {
                        Array.set(result, cnt, i);
                        cnt += 1;
                    }
                }
            } else {
                throw new TypeMismatchException(JSONArray.class, val.getClass());
            }
        } else if (val instanceof JSONObject) {
            result = JSONToObj((JSONObject) val, rawType);
        }
    }

    return result;
}

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

private static Object fromJson(Object json) {
    if (json == JSONObject.NULL || json == null) {
        return null;
    } else if (json instanceof JSONObject) {
        return toMap((JSONObject) json);
    } else if (json instanceof JSONArray) {
        return toList((JSONArray) json);
    } else {//from w w w .  ja  va  2  s . c o  m
        return json;
    }
}

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

private static Object deepCopy(Object object) {
    if (object == null) {
        return null;
    } else if (object == JSONObject.NULL) {
        return JSONObject.NULL;
    } else {/*from w  w  w  .  j  av a2s. com*/
        Class<?> c = object.getClass();
        if (c == JSONObject.class) {
            JSONObject src = ((JSONObject) object);
            JSONObject dst = new JSONObject();

            Iterator<String> srcKeys = src.keys();
            while (srcKeys.hasNext()) {
                String srcKey = srcKeys.next();
                try {
                    dst.put(srcKey, deepCopy(src.get(srcKey)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else if (c == JSONArray.class) {
            JSONArray src = ((JSONArray) object);
            JSONArray dst = new JSONArray();

            for (int i = 0, count = src.length(); i < count; i++) {
                try {
                    dst.put(deepCopy(src.get(i)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else {
            if (c == String.class || c == Long.class || c == Boolean.class || c == Integer.class
                    || c == Double.class || c == Float.class) {
                return object;
            } else {
                throw new RuntimeException("Unsupported object type: " + c.getSimpleName());
            }
        }

    }
}

From source file:org.jabsorb.ng.serializer.impl.ListSerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    final List<?> list = (List<?>) o;
    final JSONObject obj = new JSONObject();
    final JSONArray arr = new JSONArray();

    // TODO: this same block is done everywhere.
    // Have a single function to do it.
    if (ser.getMarshallClassHints()) {
        try {/*from  w w w .ja v a  2s  .  c  o m*/
            obj.put("javaClass", o.getClass().getName());
        } catch (final JSONException e) {
            throw new MarshallException("javaClass not found!", e);
        }
    }

    try {
        obj.put("list", arr);
        state.push(o, arr, "list");

    } catch (final JSONException e) {
        throw new MarshallException("Error setting list: " + e, e);
    }

    int index = 0;
    try {
        for (final Object item : list) {
            // Convert the item
            final Object json = ser.marshall(state, arr, item, index);

            // Check for circular references
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                arr.put(json);
            } else {
                // put a slot where the object would go, so it can be fixed
                // up properly in the fix up phase
                arr.put(JSONObject.NULL);
            }

            index++;
        }

    } catch (final MarshallException e) {
        throw new MarshallException("element " + index, e);

    } finally {
        state.pop();
    }

    return obj;
}

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

/**
 * This method would create a string consisting of a JSON document with all
 * the necessary elements set from the HttpServletRequest request.
 * /*from  w  w w.jav a  2  s . c  om*/
 * @param request
 *            The HttpServletRequest
 * @return the string containing the JSON document.
 * @throws Exception
 *             If there is any error processing the request.
 */
public static String createJSONString(HttpServletRequest request, String controller) throws Exception {
    JSONObject obj = new JSONObject();
    try {
        Field[] allFields = Class
                .forName("com.microsoft.windowsazure.activedirectory.sdk.graph.models." + controller)
                .getDeclaredFields();
        String[] allFieldStr = new String[allFields.length];
        for (int i = 0; i < allFields.length; i++) {
            allFieldStr[i] = allFields[i].getName();
        }
        List<String> allFieldStringList = Arrays.asList(allFieldStr);
        Enumeration<String> fields = request.getParameterNames();

        while (fields.hasMoreElements()) {

            String fieldName = fields.nextElement();
            String param = request.getParameter(fieldName);
            if (allFieldStringList.contains(fieldName)) {
                if (param == null || param.length() == 0) {
                    if (!fieldName.equalsIgnoreCase("password")) {
                        obj.put(fieldName, JSONObject.NULL);
                    }
                } else {
                    if (fieldName.equalsIgnoreCase("password")) {
                        obj.put("passwordProfile", new JSONObject("{\"password\": \"" + param + "\"}"));
                    } else {
                        obj.put(fieldName, param);

                    }
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return obj.toString();
}

From source file:com.xc0ffeelabs.taxicab.models.User.java

public void setDestLocation(LatLng location, String text) {
    if (location == null) {
        put(DEST_LOCATION, JSONObject.NULL);
    } else {//from   w  w w . ja v  a2s  . c  o  m
        Location pnt = new Location();
        pnt.setLatitude(location.latitude);
        pnt.setLongitude(location.longitude);
        if (!TextUtils.isEmpty(text)) {
            pnt.setText(text);
        }
        put(DEST_LOCATION, pnt);
    }
    saveInBackground();
}

From source file:com.skysql.manager.SystemRecord.java

/**
 * Save. Saves the newly created or modified system to the API.
 *
 * @return true, if successful/*from   ww w .j ava  2  s .  c  o m*/
 */
public boolean save() {

    APIrestful api = new APIrestful();
    boolean success = false;

    try {
        if (getID() != null) {
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("name", getName());
            jsonParam.put("systemtype", getSystemType());
            jsonParam.put("dbusername", this.dbUsername);
            jsonParam.put("dbpassword", this.dbPassword != null ? this.dbPassword : JSONObject.NULL);
            jsonParam.put("repusername", this.repUsername);
            jsonParam.put("reppassword", this.repPassword != null ? this.repPassword : JSONObject.NULL);
            success = api.put("system/" + getID(), jsonParam.toString());
        } else {
            StringBuffer regParam = new StringBuffer();
            regParam.append("name=" + URLEncoder.encode(getName(), "UTF-8"));
            regParam.append("&systemtype=" + URLEncoder.encode(getSystemType(), "UTF-8"));
            regParam.append("&dbusername=" + URLEncoder.encode(this.dbUsername, "UTF-8"));
            regParam.append("&dbpassword=" + URLEncoder.encode(this.dbPassword, "UTF-8"));
            regParam.append("&repusername=" + URLEncoder.encode(this.repUsername, "UTF-8"));
            regParam.append("&reppassword=" + URLEncoder.encode(this.repPassword, "UTF-8"));
            success = api.post("system", regParam.toString());
        }

    } catch (JSONException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    } catch (UnsupportedEncodingException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    }

    if (success) {
        WriteResponse writeResponse = APIrestful.getGson().fromJson(api.getResult(), WriteResponse.class);
        if (writeResponse != null && getID() == null && !writeResponse.getInsertKey().isEmpty()) {
            setID(writeResponse.getInsertKey());
            return true;
        } else if (writeResponse != null && getID() != null && writeResponse.getUpdateCount() > 0) {
            return true;
        }
    }

    return false;

}

From source file:net.dv8tion.jda.core.managers.impl.PresenceImpl.java

@Override
public void setPresence(OnlineStatus status, Game game, boolean idle) {
    JSONObject gameObj = getGameJson(game);

    Checks.check(status != OnlineStatus.UNKNOWN, "Cannot set the presence status to an unknown OnlineStatus!");
    if (status == OnlineStatus.OFFLINE || status == null)
        status = OnlineStatus.INVISIBLE;

    JSONObject object = new JSONObject();

    if (gameObj == null)
        object.put("game", JSONObject.NULL);
    else//from w  w  w  .j a  v  a  2s . c  o  m
        object.put("game", gameObj);
    object.put("afk", idle);
    object.put("status", status.getKey());
    object.put("since", System.currentTimeMillis());
    update(object);
    this.idle = idle;
    this.status = status;
    this.game = gameObj == null ? null : game;
}

From source file:net.dv8tion.jda.core.managers.impl.PresenceImpl.java

@Override
public void setPresence(OnlineStatus status, Game game) {
    JSONObject gameObj = getGameJson(game);

    Checks.check(status != OnlineStatus.UNKNOWN, "Cannot set the presence status to an unknown OnlineStatus!");
    if (status == OnlineStatus.OFFLINE || status == null)
        status = OnlineStatus.INVISIBLE;

    JSONObject object = new JSONObject();

    if (gameObj == null)
        object.put("game", JSONObject.NULL);
    else//from   www . j a v a 2s . co m
        object.put("game", gameObj);
    object.put("status", status.getKey());
    object.put("since", System.currentTimeMillis());
    update(object);
    this.status = status;
    this.game = gameObj == null ? null : game;
}