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:io.github.grahambell.taco.TacoTransport.java

/**
 * Convert an individual JSON entry to a Java Object.
 *
 * JSON objects and arrays are converted using the {@link #jsonToMap}
 * and {@link #jsonToList} methods.  Instances of
 * <code>Boolean</code>, <code>Number</code> and <code>String</code>
 * are returned as they are.  If an object filter has been specified
 * then its <code>mapToObject</code> method is applied to JSON
 * objects which have been conveted to <code>Map</code> instances.
 *
 * @param value an object obtained by parsing part of a JSON message
 * @return a Java representation of the value
 * @throws TacoException on error in conversion
 *//*w w  w  . ja  v  a  2s  .  c o  m*/
public Object jsonToObject(Object value) throws TacoException {
    if (JSONObject.NULL == value) {
        return null;
    } else if (value instanceof JSONObject) {
        Map<String, Object> map = jsonToMap((JSONObject) value);

        if (filter == null) {
            return map;
        } else {
            return filter.mapToObject(map);
        }
    } else if (value instanceof JSONArray) {
        return jsonToList((JSONArray) value);
    } else if ((value instanceof Boolean) || (value instanceof Number) || (value instanceof String)) {
        return value;
    } else {
        throw new TacoException("unexpected type in JSONObject");
    }
}

From source file:io.github.grahambell.taco.TacoTransport.java

/**
 * Convert an individual Java object to an object suitable for
 * representation in JSON./*from w w w  . j  ava  2  s  . c  o m*/
 *
 * Instances of <code>Map</code> and <code>Collection</code>
 * are converted using the {@link #mapToJson} and {@link #collectionToJson}
 * methods.  Null entries are converted to JSON null values.
 * Instances of <code>Boolean</code>, <code>Number</code> and
 * <code>String</code> are returned as they are.  If an object filter
 * has been specified then its <code>objectToMap</code> is applied
 * to any other type of value.  When no filter has been provided
 * and an unknown object type is encountered, an exception is thrown.
 *
 * @param value the input object
 * @return an object suitable for representation in JSON
 * @throws TacoException on error in conversion
 */
public Object objectToJson(Object value) throws TacoException {
    if (value == null) {
        return JSONObject.NULL;
    } else if (value instanceof Map) {
        return mapToJson((Map<String, Object>) value);
    } else if (value instanceof Collection) {
        return collectionToJson((Collection<Object>) value);
    } else if ((value instanceof Boolean) || (value instanceof Number) || (value instanceof String)) {
        return value;
    } else {
        if (filter == null) {
            throw new TacoException("unknown object type to turn to JSON");
        } else {
            return mapToJson(filter.objectToMap(value));
        }
    }
}

From source file:vOS.controller.socket.IOConnection.java

/**
 * Creates a new {@link IOAcknowledge} instance which sends its arguments
 * back to the server.//w ww .  j  a  v  a 2s .  c  o m
 * 
 * @param message
 *            the message
 * @return an {@link IOAcknowledge} instance, may be <code>null</code> if
 *         server doesn't request one.
 */
private IOAcknowledge remoteAcknowledge(IOMessage message) {
    String _id = message.getId();
    if (_id.equals(""))
        return null;
    else if (_id.endsWith("+") == false)
        _id = _id + "+";
    final String id = _id;
    final String endPoint = message.getEndpoint();
    return new IOAcknowledge() {
        @Override
        public void ack(Object... args) {
            JSONArray array = new JSONArray();
            for (Object o : args) {
                try {
                    array.put(o == null ? JSONObject.NULL : o);
                } catch (Exception e) {
                    error(new SocketIOException(
                            "You can only put values in IOAcknowledge.ack() which can be handled by JSONArray.put()",
                            e));
                }
            }
            IOMessage ackMsg = new IOMessage(IOMessage.TYPE_ACK, endPoint, id + array.toString());
            sendPlain(ackMsg.toString());
        }
    };
}

From source file:org.everit.json.schema.ValidationExceptionTest.java

@Test
public void toJSONNullPointerToViolation() {
    ValidationException subject = new ValidationException(BooleanSchema.INSTANCE, null, "exception message",
            Collections.emptyList(), "type");
    JSONObject actual = subject.toJSON();
    Assert.assertEquals(JSONObject.NULL, actual.get("pointerToViolation"));
}

From source file:com.richtodd.android.quiltdesign.block.Quilt.java

JSONObject createJSONObject() throws JSONException {

    JSONArray jsonQuiltBlocks = new JSONArray();
    for (int row = 0; row < m_rowCount; ++row) {
        for (int column = 0; column < m_columnCount; ++column) {
            QuiltBlock quiltBlock = getQuiltBlock(row, column);
            if (quiltBlock != null) {
                jsonQuiltBlocks.put(quiltBlock.createJSONObject());
            } else {
                jsonQuiltBlocks.put(JSONObject.NULL);
            }//  ww  w  .ja  va  2 s .  c  om
        }
    }

    JSONObject jsonQuilt = new JSONObject();
    jsonQuilt.put("objectType", "quilt");
    jsonQuilt.put("rowCount", m_rowCount);
    jsonQuilt.put("columnCount", m_columnCount);
    jsonQuilt.put("width", m_width);
    jsonQuilt.put("height", m_height);
    jsonQuilt.put("quiltBlocks", jsonQuiltBlocks);

    return jsonQuilt;
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

public static JSONObject fillBasicInfo(JSONObject object, Context ctx) throws JSONException {
    object.put("plattform", PLATTFORM_NAME);
    object.put("os_version",
            android.os.Build.VERSION.RELEASE + "(" + android.os.Build.VERSION.INCREMENTAL + ")");
    object.put("api_level", String.valueOf(android.os.Build.VERSION.SDK_INT));
    object.put("device", android.os.Build.DEVICE);
    object.put("model", android.os.Build.MODEL);
    object.put("product", android.os.Build.PRODUCT);
    object.put("language", Locale.getDefault().getLanguage());
    object.put("timezone", TimeZone.getDefault().getID());
    object.put("softwareRevision", RevisionHelper.getVerboseRevision());
    PackageInfo pInfo = getPackageInfo(ctx);
    if (pInfo != null) {
        object.put("softwareVersionCode", pInfo.versionCode);
        object.put("softwareVersionName", pInfo.versionName);
    }/*from   www.j  ava2 s .c om*/
    object.put("type", at.alladin.rmbt.android.util.Config.RMBT_CLIENT_TYPE);

    if (BASIC_INFORMATION_INCLUDE_LOCATION) {
        Location loc = GeoLocation.getLastKnownLocation(ctx);
        if (loc != null) {
            JSONObject locationJson = new JSONObject();
            locationJson.put("lat", loc.getLatitude());
            locationJson.put("long", loc.getLongitude());
            locationJson.put("provider", loc.getProvider());
            if (loc.hasSpeed())
                locationJson.put("speed", loc.getSpeed());
            if (loc.hasAltitude())
                locationJson.put("altitude", loc.getAltitude());
            locationJson.put("age", System.currentTimeMillis() - loc.getTime()); //getElapsedRealtimeNanos() would be better, but require higher API-level
            if (loc.hasAccuracy())
                locationJson.put("accuracy", loc.getAccuracy());
            if (loc.hasSpeed())
                locationJson.put("speed", loc.getSpeed());
            /*
             *  would require API level 18
            if (loc.isFromMockProvider())
               locationJson.put("mock",loc.isFromMockProvider());
            */
            object.put("location", locationJson);
        }
    }

    InformationCollector infoCollector = null;

    if (ctx instanceof RMBTMainActivity) {
        Fragment curFragment = ((RMBTMainActivity) ctx).getCurrentFragment();
        if (curFragment != null) {
            if (curFragment instanceof RMBTMainMenuFragment) {
                infoCollector = ((RMBTMainMenuFragment) curFragment).getInformationCollector();
            }
        }
    }

    if (BASIC_INFORMATION_INCLUDE_LAST_SIGNAL_ITEM && (infoCollector != null)) {
        SignalItem signalItem = infoCollector.getLastSignalItem();
        if (signalItem != null) {
            object.put("last_signal_item", signalItem.toJson());
        } else {
            object.put("last_signal_item", JSONObject.NULL);
        }
    }

    return object;
}

From source file:org.everit.json.schema.ValidationException.java

/**
 * Creates a JSON representation of the failure.
 *
 * The returned {@code JSONObject} contains the following keys:
 * <ul>//from  www .  j  a v a  2  s.co  m
 * <li>{@code "message"}: a programmer-friendly exception message. This value is a non-nullable
 * string.</li>
 * <li>{@code "keyword"}: a JSON Schema keyword which was used in the schema and violated by the
 * input JSON. This value is a nullable string.</li>
 * <li>{@code "pointerToViolation"}: a JSON Pointer denoting the path from the root of the
 * document to the invalid fragment of it. This value is a non-nullable string. See
 * {@link #getPointerToViolation()}</li>
 * <li>{@code "causingExceptions"}: is a (possibly empty) array of violations which caused this
 * exceptions. See {@link #getCausingExceptions()}</li>
 * </ul>
 *
 * @return a JSON description of the validation error
 */
public JSONObject toJSON() {
    JSONObject rval = new JSONObject();
    rval.put("keyword", keyword);
    if (pointerToViolation == null) {
        rval.put("pointerToViolation", JSONObject.NULL);
    } else {
        rval.put("pointerToViolation", getPointerToViolation());
    }
    rval.put("message", super.getMessage());
    List<JSONObject> causeJsons = causingExceptions.stream().map(ValidationException::toJSON)
            .collect(Collectors.toList());
    rval.put("causingExceptions", new JSONArray(causeJsons));
    return rval;
}

From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java

private OctaneEntity parseEntity(JSONObject entObj) {

    String type = entObj.getString("type");

    OctaneEntity entity = createEntity(type);
    for (String key : entObj.keySet()) {
        Object value = entObj.get(key);
        if (value instanceof JSONObject) {
            JSONObject jObj = (JSONObject) value;
            if (jObj.has("type")) {
                OctaneEntity valueEntity = parseEntity(jObj);
                value = valueEntity;// ww w .j  a  v a 2 s  .co m
            } else if (jObj.has("total_count")) {
                OctaneEntityCollection coll = parseCollection(jObj);
                value = coll;
            } else {
                value = jObj.toString();
            }
        } else if (JSONObject.NULL.equals(value)) {
            value = null;
        }
        entity.put(key, value);
    }
    return entity;
}

From source file:net.dv8tion.jda.core.managers.AccountManagerUpdatable.java

/**
 * Creates a new {@link net.dv8tion.jda.core.requests.RestAction RestAction} instance
 * that will apply <b>all</b> changes that have been made to this manager instance.
 *
 * <p>Before applying new changes it is recommended to call {@link #reset()} to reset previous changes.
 * <br>This is automatically called if this method returns successfully.
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} for this
 * update include the following://from   w  w w . jav  a  2 s . co m
 * <ul>
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#INVALID_PASSWORD INVALID_PASSWORD}
 *      <br>If the specified {@code currentPassword} is not a valid password</li>
 * </ul>
 *
 * @param  currentPassword
 *         Used for accounts from {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT},
 *         provide {@code null} if this is not a client-account
 *
 * @throws IllegalArgumentException
 *         If the provided password is null or empty and the currently logged in account
 *         is from {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT}
 *
 * @return {@link net.dv8tion.jda.core.requests.RestAction RestAction}
 *         <br>Updates all modified fields or does nothing if none of the {@link net.dv8tion.jda.core.managers.fields.Field Fields}
 *         have been modified. ({@link net.dv8tion.jda.core.requests.RestAction.EmptyRestAction EmptyRestAction})
 */
@CheckReturnValue
public RestAction<Void> update(String currentPassword) {
    if (isType(AccountType.CLIENT) && (currentPassword == null || currentPassword.isEmpty()))
        throw new IllegalArgumentException(
                "Provided client account password to be used in auth is null or empty!");

    if (!needToUpdate())
        return new RestAction.EmptyRestAction<>(getJDA(), null);

    JSONObject body = new JSONObject();

    //Required fields. Populate with current values..
    body.put("username", name.getOriginalValue());
    body.put("avatar", selfUser.getAvatarId() != null ? selfUser.getAvatarId() : JSONObject.NULL);

    if (name.shouldUpdate())
        body.put("username", name.getValue());
    if (avatar.shouldUpdate())
        body.put("avatar", avatar.getValue() != null ? avatar.getValue().getEncoding() : JSONObject.NULL);

    if (isType(AccountType.CLIENT)) {
        //Required fields. Populate with current values.
        body.put("password", currentPassword);
        body.put("email", email.getOriginalValue());

        if (email.shouldUpdate())
            body.put("email", email.getValue());
        if (password.shouldUpdate())
            body.put("new_password", password.getValue());
    }

    reset(); //now that we've built our JSON object, reset the manager back to the non-modified state
    Route.CompiledRoute route = Route.Self.MODIFY_SELF.compile();
    return new RestAction<Void>(getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (!response.isOk()) {
                request.onFailure(response);
                return;
            }

            String newToken = response.getObject().getString("token");
            newToken = newToken.replace("Bot ", "");

            api.setToken(newToken);
            request.onSuccess(null);
        }
    };
}

From source file:com.github.socialc0de.gsw.android.MainActivity.java

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<String, Object>();

    if (json != JSONObject.NULL) {
        retMap = toMap(json);/*from ww w  .j  av  a2  s  .co  m*/
    }
    return retMap;
}