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:run.ace.IncomingMessages.java

public static void fieldSet(JSONArray message) throws JSONException {
    Object instance = Handle.deserialize(message.getJSONObject(1));
    String fieldName = message.getString(2);
    Object fieldValue = message.get(3);

    // Convert non-primitives
    if (fieldValue instanceof JSONObject) {
        fieldValue = Utils.deserializeObjectOrStruct((JSONObject) fieldValue);
    } else if (fieldValue == JSONObject.NULL) {
        fieldValue = null;/*ww w. j av  a 2s.  c  o m*/
    }

    Utils.setField(instance.getClass(), instance, fieldName, fieldValue);
}

From source file:net.dv8tion.jda.core.managers.ChannelManagerUpdatable.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.
 * <br>If no changes have been made this will simply return {@link net.dv8tion.jda.core.requests.RestAction.EmptyRestAction EmptyRestAction}.
 *
 * <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 .java  2  s.  c om
 * <ul>
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *      <br>If the Channel was deleted before finishing the task</li>
 *
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *      <br>If the currently logged in account was removed from the Guild before finishing the task</li>
 *
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *      <br>If the currently logged in account loses the {@link net.dv8tion.jda.core.Permission#MANAGE_CHANNEL MANAGE_CHANNEL Permission}
 *          before finishing the task</li>
 * </ul>
 *
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the currently logged in account does not have the Permission {@link net.dv8tion.jda.core.Permission#MANAGE_CHANNEL MANAGE_CHANNEL}
 *         in the underlying {@link net.dv8tion.jda.core.entities.Channel Channel}.
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction}
 *         <br>Applies all changes that have been made in a single api-call.
 */
@CheckReturnValue
public AuditableRestAction<Void> update() {
    checkPermission(Permission.MANAGE_CHANNEL);

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

    JSONObject frame = new JSONObject().put("name", channel.getName());
    if (name.shouldUpdate())
        frame.put("name", name.getValue());
    if (topic != null && topic.shouldUpdate())
        frame.put("topic", topic.getValue() == null ? JSONObject.NULL : topic.getValue());
    if (nsfw != null && nsfw.shouldUpdate())
        frame.put("nsfw", nsfw.getValue());
    if (userLimit != null && userLimit.shouldUpdate())
        frame.put("user_limit", userLimit.getValue());
    if (bitrate != null && bitrate.shouldUpdate())
        frame.put("bitrate", bitrate.getValue());

    reset(); //now that we've built our JSON object, reset the manager back to the non-modified state
    Route.CompiledRoute route = Route.Channels.MODIFY_CHANNEL.compile(channel.getId());
    return new AuditableRestAction<Void>(channel.getJDA(), route, frame) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (response.isOk())
                request.onSuccess(null);
            else
                request.onFailure(response);
        }
    };
}

From source file:org.zaizi.sensefy.api.utils.JSONHelper.java

private static Object fromJson(Object json) throws JSONException {
    if (json == JSONObject.NULL) {
        return null;
    } else if (json instanceof JSONObject) {
        return toMap((JSONObject) json);
    } else if (json instanceof JSONArray) {
        return toList((JSONArray) json);
    } else {/*from  ww w  .  j ava2  s. c  om*/
        return json;
    }
}

From source file:io.riddles.lightriders.game.state.LightridersStateSerializer.java

private JSONObject visitState(LightridersState state) {
    JSONObject stateJson = new JSONObject();
    stateJson.put("round", state.getRoundNumber());

    JSONArray players = new JSONArray();
    for (LightridersPlayerState playerState : state.getPlayerStates()) {
        JSONObject playerObj = new JSONObject();
        playerObj.put("id", playerState.getPlayerId());
        playerObj.put("position", visitPoint(playerState.getCoordinate()));
        playerObj.put("isCrashed", !playerState.isAlive());

        if (playerState.getMove() != null && playerState.getMove().getException() != null) {
            playerObj.put("error", playerState.getMove().getException().getMessage());
        } else {/*from w  ww  .j  a va 2s  .  c  o  m*/
            playerObj.put("error", JSONObject.NULL);
        }

        players.put(playerObj);
    }

    stateJson.put("players", players);
    return stateJson;
}

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

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

    // reprocess the raw json in order to fixup circular references and
    // duplicates
    final JSONArray jsonIn = (JSONArray) o;
    final JSONArray jsonOut = new JSONArray();

    int i = 0;//w ww .j a  v a  2s .co  m
    try {
        final int j = jsonIn.length();

        for (i = 0; i < j; i++) {
            final Object json = ser.marshall(state, o, jsonIn.get(i), new Integer(i));
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                jsonOut.put(i, json);
            } else {
                // put a slot where the object would go, so it can be fixed
                // up properly in the fix up phase
                jsonOut.put(i, JSONObject.NULL);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("element " + i, e);
    } catch (final JSONException e) {
        throw new MarshallException("element " + i, e);
    }
    return jsonOut;
}

From source file:com.vinexs.tool.XML.java

/**
 * Convert a string to its possible data type.
 *
 * @param string String to be converted.
 * @return Value in Boolean, Null, Integer, Double or String.
 *///from   w  ww.  j ava 2s .c o m
public static Object stringToValue(String string) {
    if ("true".equalsIgnoreCase(string)) {
        return Boolean.TRUE;
    }
    if ("false".equalsIgnoreCase(string)) {
        return Boolean.FALSE;
    }
    if ("null".equalsIgnoreCase(string)) {
        return JSONObject.NULL;
    }
    if (Determinator.isNumeric(string)) {
        if (Determinator.isInteger(string)) {
            Integer strInt = Integer.valueOf(string);
            if (strInt.toString().equals(string)) {
                return strInt;
            }
        }
        return Double.valueOf(string);
    }
    return string;
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void generateAndSendGeoJsonToolReport() {
    FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();
    JSONObject featureCollection = new JSONObject();

    try {//from  www  . j a v  a 2  s .c o m
        Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet();
        JSONArray featureList = new JSONArray();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED
                        || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                }

                toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        : ToolEntryStatus.STATUS_SENT_UNCONFIRMED);
                JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker);
                featureList.put(gjsonTool);
            }
        }

        if (featureList.length() == 0) {
            Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show();

            return;
        }

        user.writeToSharedPref(getActivity());
        featureCollection.put("features", featureList);
        featureCollection.put("type", "FeatureCollection");
        featureCollection.put("crs", JSONObject.NULL);
        featureCollection.put("bbox", JSONObject.NULL);

        String toolString = featureCollection.toString(4);

        if (fiskInfoUtility.isExternalStorageWritable()) {
            fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(),
                    getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false);
            String directoryPath = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            String fileName = directoryPath + "/FiskInfo/api_setting.json";
            File apiSettingsFile = new File(fileName);
            String recipient = null;

            if (apiSettingsFile.exists()) {
                InputStream inputStream;
                InputStreamReader streamReader;
                JsonReader jsonReader;

                try {
                    inputStream = new BufferedInputStream(new FileInputStream(apiSettingsFile));
                    streamReader = new InputStreamReader(inputStream, "UTF-8");
                    jsonReader = new JsonReader(streamReader);

                    jsonReader.beginObject();
                    while (jsonReader.hasNext()) {
                        String name = jsonReader.nextName();
                        if (name.equals("email")) {
                            recipient = jsonReader.nextString();
                        } else {
                            jsonReader.skipValue();
                        }
                    }
                    jsonReader.endObject();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }

            recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient;
            String[] recipients = new String[] { recipient };
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/plain");

            String toolIds;
            StringBuilder sb = new StringBuilder();

            sb.append("Redskapskoder:\n");

            for (int i = 0; i < featureList.length(); i++) {
                sb.append(Integer.toString(i + 1));
                sb.append(": ");
                sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId"));
                sb.append("\n");
            }

            toolIds = sb.toString();

            intent.putExtra(Intent.EXTRA_EMAIL, recipients);
            intent.putExtra(Intent.EXTRA_TEXT, toolIds);
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header));
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()
                            + "/FiskInfo/Redskapsrapport.geojson");
            Uri uri = Uri.fromFile(file);
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header)));

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.uiautomation.ios.server.command.web.SetFrameHandler.java

@Override
public Response handle() throws Exception {
    Object p = getRequest().getPayload().get("id");

    if (JSONObject.NULL.equals(p)) {
        getSession().getContext().getDOMContext().setCurrentFrame(null, null, null);
    } else {//from   w  w  w  . j  a va 2 s  . co m
        RemoteWebElement iframe;
        if (p instanceof String) {
            iframe = getIframe((String) p);
        } else if (p instanceof Integer) {
            iframe = getIframe((Integer) p);
        } else if (p instanceof JSONObject) {
            String id = ((JSONObject) p).getString("ELEMENT");
            NodeId node = new NodeId(Integer.parseInt(id));
            iframe = new RemoteWebElement(node, getSession());
        } else {
            throw new UnsupportedCommandException("not supported : frame selection by " + p.getClass());
        }

        RemoteWebElement document = iframe.getContentDocument();
        RemoteWebElement window = iframe.getContentWindow();
        getSession().getContext().getDOMContext().setCurrentFrame(iframe, document, window);
    }

    Response res = new Response();
    res.setSessionId(getSession().getSessionId());
    res.setStatus(0);
    res.setValue(new JSONObject());
    return res;
}

From source file:com.android.aft.AFCuteJsonParser.AFJsonValue.java

public AFJsonValue(String name, Object json) {
    mName = name;//from ww w .j  a  v  a 2 s.c  o m

    if (json instanceof JSONObject) {
        mType = JsonValueType.JsonObject;
        mJsonObject = (JSONObject) json;
        mChildren = new ArrayList<AFJsonValue>();
        try {
            Iterator<?> keys = mJsonObject.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                mChildren.add(new AFJsonValue(key, mJsonObject.get(key)));
            }
        } catch (JSONException e) {
        }
    } else if (json instanceof JSONArray) {
        mType = JsonValueType.JsonArray;
        mJsonArray = (JSONArray) json;
        mChildren = new ArrayList<AFJsonValue>();
        try {
            for (int i = 0; i < mJsonArray.length(); ++i)
                mChildren.add(new AFJsonValue("" + i, mJsonArray.get(i)));
        } catch (JSONException e) {
        }
    } else if (json instanceof String) {
        mType = JsonValueType.JsonString;
        mJsonString = (String) json;
    } else if (json instanceof Number) {
        mType = JsonValueType.JsonNumber;
        mJsonNumber = (Number) json;
    } else if (json instanceof Boolean) {
        mType = JsonValueType.JsonBoolean;
        mJsonBoolean = ((Boolean) json).booleanValue();
    } else if (json.equals(JSONObject.NULL)) {
        mType = JsonValueType.JsonNull;
    } else
        mType = JsonValueType.None;
}

From source file:com.jsonstore.jackson.JsonOrgJSONArraySerializer.java

private void serializeContents(JSONArray value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    int length = value.length();

    for (int i = 0; i < length; ++i) {
        Class<?> cls;//from  ww  w .  java 2s.  c  o  m
        Object obj = value.opt(i);

        if ((obj == null) || (obj == JSONObject.NULL)) {
            jgen.writeNull();

            continue;
        }

        cls = obj.getClass();

        if ((cls == JSONObject.class) || JSONObject.class.isAssignableFrom(cls)) {
            JsonOrgJSONObjectSerializer.instance.serialize((JSONObject) obj, jgen, provider);
        }

        else if ((cls == JSONArray.class) || JSONArray.class.isAssignableFrom(cls)) {
            serialize((JSONArray) obj, jgen, provider);
        }

        else if (cls == String.class) {
            jgen.writeString((String) obj);
        }

        else if (cls == Integer.class) {
            jgen.writeNumber(((Integer) obj).intValue());
        }

        else if (cls == Long.class) {
            jgen.writeNumber(((Long) obj).longValue());
        }

        else if (cls == Boolean.class) {
            jgen.writeBoolean(((Boolean) obj).booleanValue());
        }

        else if (cls == Double.class) {
            jgen.writeNumber(((Double) obj).doubleValue());
        }

        else {
            provider.defaultSerializeValue(obj, jgen);
        }
    }
}