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:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java

private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor) throws JSONException {
    Object value = bundle.get(key);
    if (value == null) {
        // Cannot serialize null values.
        return;//ww w  . j  a v  a 2 s. c  o  m
    }

    String supportedType = null;
    JSONArray jsonArray = null;
    JSONObject json = new JSONObject();

    if (value instanceof Byte) {
        supportedType = TYPE_BYTE;
        json.put(JSON_VALUE, ((Byte) value).intValue());
    } else if (value instanceof Short) {
        supportedType = TYPE_SHORT;
        json.put(JSON_VALUE, ((Short) value).intValue());
    } else if (value instanceof Integer) {
        supportedType = TYPE_INTEGER;
        json.put(JSON_VALUE, ((Integer) value).intValue());
    } else if (value instanceof Long) {
        supportedType = TYPE_LONG;
        json.put(JSON_VALUE, ((Long) value).longValue());
    } else if (value instanceof Float) {
        supportedType = TYPE_FLOAT;
        json.put(JSON_VALUE, ((Float) value).doubleValue());
    } else if (value instanceof Double) {
        supportedType = TYPE_DOUBLE;
        json.put(JSON_VALUE, ((Double) value).doubleValue());
    } else if (value instanceof Boolean) {
        supportedType = TYPE_BOOLEAN;
        json.put(JSON_VALUE, ((Boolean) value).booleanValue());
    } else if (value instanceof Character) {
        supportedType = TYPE_CHAR;
        json.put(JSON_VALUE, value.toString());
    } else if (value instanceof String) {
        supportedType = TYPE_STRING;
        json.put(JSON_VALUE, (String) value);
    } else if (value instanceof Enum<?>) {
        supportedType = TYPE_ENUM;
        json.put(JSON_VALUE, value.toString());
        json.put(JSON_VALUE_ENUM_TYPE, value.getClass().getName());
    } else {
        // Optimistically create a JSONArray. If not an array type, we can null
        // it out later
        jsonArray = new JSONArray();
        if (value instanceof byte[]) {
            supportedType = TYPE_BYTE_ARRAY;
            for (byte v : (byte[]) value) {
                jsonArray.put((int) v);
            }
        } else if (value instanceof short[]) {
            supportedType = TYPE_SHORT_ARRAY;
            for (short v : (short[]) value) {
                jsonArray.put((int) v);
            }
        } else if (value instanceof int[]) {
            supportedType = TYPE_INTEGER_ARRAY;
            for (int v : (int[]) value) {
                jsonArray.put(v);
            }
        } else if (value instanceof long[]) {
            supportedType = TYPE_LONG_ARRAY;
            for (long v : (long[]) value) {
                jsonArray.put(v);
            }
        } else if (value instanceof float[]) {
            supportedType = TYPE_FLOAT_ARRAY;
            for (float v : (float[]) value) {
                jsonArray.put((double) v);
            }
        } else if (value instanceof double[]) {
            supportedType = TYPE_DOUBLE_ARRAY;
            for (double v : (double[]) value) {
                jsonArray.put(v);
            }
        } else if (value instanceof boolean[]) {
            supportedType = TYPE_BOOLEAN_ARRAY;
            for (boolean v : (boolean[]) value) {
                jsonArray.put(v);
            }
        } else if (value instanceof char[]) {
            supportedType = TYPE_CHAR_ARRAY;
            for (char v : (char[]) value) {
                jsonArray.put(String.valueOf(v));
            }
        } else if (value instanceof List<?>) {
            supportedType = TYPE_STRING_LIST;
            @SuppressWarnings("unchecked")
            List<String> stringList = (List<String>) value;
            for (String v : stringList) {
                jsonArray.put((v == null) ? JSONObject.NULL : v);
            }
        } else {
            // Unsupported type. Clear out the array as a precaution even though
            // it is redundant with the null supportedType.
            jsonArray = null;
        }
    }

    if (supportedType != null) {
        json.put(JSON_VALUE_TYPE, supportedType);
        if (jsonArray != null) {
            // If we have an array, it has already been converted to JSON. So use
            // that instead.
            json.putOpt(JSON_VALUE, jsonArray);
        }

        String jsonString = json.toString();
        editor.putString(key, jsonString);
    }
}

From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }/*from   w ww . j a va2 s.  c o m*/
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:com.facebook.share.internal.OpenGraphJSONUtility.java

public static Object toJSONValue(@Nullable final Object object, final PhotoJSONProcessor photoJSONProcessor)
        throws JSONException {
    if (object == null) {
        return JSONObject.NULL;
    }// ww w. ja  va2s . c  o  m
    if ((object instanceof String) || (object instanceof Boolean) || (object instanceof Double)
            || (object instanceof Float) || (object instanceof Integer) || (object instanceof Long)) {
        return object;
    }
    if (object instanceof SharePhoto) {
        if (photoJSONProcessor != null) {
            return photoJSONProcessor.toJSONObject((SharePhoto) object);
        }
        return null;
    }
    if (object instanceof ShareOpenGraphObject) {
        return toJSONObject((ShareOpenGraphObject) object, photoJSONProcessor);
    }
    if (object instanceof List) {
        return toJSONArray((List) object, photoJSONProcessor);
    }
    throw new IllegalArgumentException("Invalid object found for JSON serialization: " + object.toString());
}

From source file:com.unboundid.scim.sdk.FilterParser.java

/**
 * Read a value at the current position. A value can be a number, a datetime
 * or a boolean value (the words true or false), or a string value in double
 * quotes, using the same syntax as for JSON values. Whitespace before and
 * after the value is consumed. The start of the value is saved in
 * {@code markPos}.//  w w w.  ja  va 2s .c  o m
 *
 * @return A String representing the value at the current position, or
 *         {@code null} if the end of the input has already been reached.
 */
public String readValue() {
    skipWhitespace();
    markPos = currentPos;

    if (currentPos == endPos) {
        return null;
    }

    if (filterString.charAt(currentPos) == '"') {
        currentPos++;

        final StringBuilder builder = new StringBuilder();
        while (currentPos < endPos) {
            final char c = filterString.charAt(currentPos);
            switch (c) {
            case '\\':
                currentPos++;
                if (endOfInput()) {
                    final String msg = String
                            .format("End of input in a string value that began at " + "position %d", markPos);
                    throw new IllegalArgumentException(msg);
                }
                final char escapeChar = filterString.charAt(currentPos);
                currentPos++;
                switch (escapeChar) {
                case '"':
                case '/':
                case '\'':
                case '\\':
                    builder.append(escapeChar);
                    break;
                case 'b':
                    builder.append('\b');
                    break;
                case 'f':
                    builder.append('\f');
                    break;
                case 'n':
                    builder.append('\n');
                    break;
                case 'r':
                    builder.append('\r');
                    break;
                case 't':
                    builder.append('\t');
                    break;
                case 'u':
                    if (currentPos + 4 > endPos) {
                        final String msg = String.format(
                                "End of input in a string value that began at " + "position %d", markPos);
                        throw new IllegalArgumentException(msg);
                    }
                    final String hexChars = filterString.substring(currentPos, currentPos + 4);
                    builder.append((char) Integer.parseInt(hexChars, 16));
                    currentPos += 4;
                    break;
                default:
                    final String msg = String.format(
                            "Unrecognized escape sequence '\\%c' in a string value " + "at position %d",
                            escapeChar, currentPos - 2);
                    throw new IllegalArgumentException(msg);
                }
                break;

            case '"':
                currentPos++;
                skipWhitespace();
                return builder.toString();

            default:
                builder.append(c);
                currentPos++;
                break;
            }
        }

        final String msg = String.format("End of input in a string value that began at " + "position %d",
                markPos);
        throw new IllegalArgumentException(msg);
    } else {
        loop: while (currentPos < endPos) {
            final char c = filterString.charAt(currentPos);
            switch (c) {
            case ' ':
            case '(':
            case ')':
                break loop;

            case '+':
            case '-':
            case '.':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case 'a':
            case 'b':
            case 'c':
            case 'd':
            case 'e':
            case 'f':
            case 'g':
            case 'h':
            case 'i':
            case 'j':
            case 'k':
            case 'l':
            case 'm':
            case 'n':
            case 'o':
            case 'p':
            case 'q':
            case 'r':
            case 's':
            case 't':
            case 'u':
            case 'v':
            case 'w':
            case 'x':
            case 'y':
            case 'z':
                // These are all OK.
                currentPos++;
                break;

            case '/':
            case ':':
            case ';':
            case '<':
            case '=':
            case '>':
            case '?':
            case '@':
            case '[':
            case '\\':
            case ']':
            case '^':
            case '_':
            case '`':
                // These are not allowed, but they are explicitly called out because
                // they are included in the range of values between '-' and 'z', and
                // making sure all possible characters are included can help make
                // the switch statement more efficient.  We'll fall through to the
                // default clause to reject them.
            default:
                final String msg = String.format(
                        "Invalid character '%c' in a number or boolean value at " + "position %d", c,
                        currentPos);
                throw new IllegalArgumentException(msg);
            }
        }

        final String s = filterString.substring(markPos, currentPos);
        skipWhitespace();
        final Object value = JSONObject.stringToValue(s);
        if (value.equals(JSONObject.NULL) || value instanceof String) {
            final String msg = String.format("Invalid filter value beginning at position %d", markPos);
            throw new IllegalArgumentException(msg);
        }

        return s;
    }
}

From source file:cn.ttyhuo.view.UserView.java

private int setupTruckInfo(Context context, JSONObject jObject, JSONObject jsonObject, int verifyFlag)
        throws JSONException {
    if (JSONUtil.getBoolFromJson(jObject, "driverVerify")) {
        verifyFlag += 2;/* w  w w  .  jav a 2 s.  co m*/
    }

    if (jObject.get("truckInfo") == JSONObject.NULL) {
        ly_truck.setVisibility(View.GONE);
        if (line_truck != null)
            line_truck.setVisibility(View.GONE);

        if (line_route != null)
            line_route.setVisibility(View.GONE);
        if (ly_route != null)
            ly_route.setVisibility(View.GONE);

        if (ll_driverAge != null)
            ll_driverAge.setVisibility(View.GONE);

        tv_licensePlate.setVisibility(View.GONE);

        if (tv_driverShuoShuo != null)
            tv_driverShuoShuo.setVisibility(View.GONE);
    } else {
        ly_truck.setVisibility(View.VISIBLE);
        if (line_truck != null)
            line_truck.setVisibility(View.VISIBLE);

        if (ly_route != null)
            ly_route.setVisibility(View.GONE);
        if (line_route != null)
            line_route.setVisibility(View.GONE);
        //            try{
        //                if(jsonObject.has("userRoutes") && jsonObject.getJSONArray("userRoutes").length() > 0)
        //                    ly_route.setVisibility(View.VISIBLE);
        //                else
        //                    ly_route.setVisibility(View.GONE);
        //            }
        //            catch (Exception e){}
        if (ll_driverAge != null)
            ll_driverAge.setVisibility(View.VISIBLE);
        tv_licensePlate.setVisibility(View.VISIBLE);

        try {
            JSONObject truckInfoJsonObj = jObject.getJSONObject("truckInfo");

            Integer truckType = JSONUtil.getIntFromJson(truckInfoJsonObj, "truckType", 0);
            if (truckType != null && truckType > 0)
                tv_truckType.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                tv_truckType.setText("");

            JSONUtil.setValueFromJson(tv_licensePlate, truckInfoJsonObj, "licensePlate", "", true);

            //NOTE:  tv_truckWidth 
            if (tv_truckWidth == null) {
                tv_loadLimit.setText(context.getResources().getString(R.string.user_loadLimitStr,
                        JSONUtil.getStringFromJson(truckInfoJsonObj, "loadLimit", "")));
                tv_truckLength.setText(context.getResources().getString(R.string.user_truckLengthStr,
                        JSONUtil.getStringFromJson(truckInfoJsonObj, "truckLength", "")));
            } else {
                JSONUtil.setValueFromJson(tv_loadLimit, truckInfoJsonObj, "loadLimit", 0.0, "", true);
                JSONUtil.setValueFromJson(tv_truckLength, truckInfoJsonObj, "truckLength", 0.0, "", true);
            }

            JSONUtil.setValueFromJson(tv_truckWidth, truckInfoJsonObj, "truckWidth", 0, "", true);
            JSONUtil.setValueFromJson(tv_truckHeight, truckInfoJsonObj, "truckHeight", 0, "", true);
            JSONUtil.setValueFromJson(tv_modelNumber, truckInfoJsonObj, "modelNumber", "");
            JSONUtil.setValueFromJson(tv_seatingCapacity, truckInfoJsonObj, "seatingCapacity", 0, "",
                    true);

            if (tv_driverShuoShuo != null) {
                String tmpValue = JSONUtil.getStringFromJson(truckInfoJsonObj, "memo", "");
                if (tmpValue.isEmpty())
                    tv_driverShuoShuo.setVisibility(View.GONE);
                else {
                    tv_driverShuoShuo.setVisibility(View.VISIBLE);
                    //NOTE:  tv_truckWidth 
                    if (tv_truckWidth == null && tmpValue.length() > 38)
                        tmpValue = tmpValue.substring(0, 35) + "...";
                    tv_driverShuoShuo.setText(tmpValue);
                }
            }

            int driverAge = JSONUtil.getIntFromJson(truckInfoJsonObj, "releaseYear", 0);
            if (driverAge > 0) {
                Integer age = new Date().getYear() + 1900 - driverAge;
                tv_driverAge.setText(context.getResources().getString(R.string.user_driverAgeStr, age));
            } else {
                tv_driverAge.setText("");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return verifyFlag;
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * 1. Resets profile to get fresh slate// w w w . j ava2s . c om
 * 2. Updates active server group to one from json
 * 3. For each path in json, sets request/response enabled
 * 4. Adds active overrides to each path
 * 5. Update arguments and repeat count for each override
 *
 * @param profileBackup JSON containing server configuration and overrides to activate
 * @param profileId Profile to update
 * @param clientUUID Client UUID to apply update to
 * @return
 * @throws Exception Array of errors for things that could not be imported
 */
public void setProfileFromBackup(JSONObject profileBackup, int profileId, String clientUUID) throws Exception {
    // Reset the profile before applying changes
    ClientService clientService = ClientService.getInstance();
    clientService.reset(profileId, clientUUID);
    clientService.updateActive(profileId, clientUUID, true);
    JSONArray errors = new JSONArray();

    // Change to correct server group
    JSONObject activeServerGroup = profileBackup.getJSONObject(Constants.BACKUP_ACTIVE_SERVER_GROUP);
    int activeServerId = getServerIdFromName(activeServerGroup.getString(Constants.NAME), profileId);
    if (activeServerId == -1) {
        errors.put(formErrorJson("Server Error", "Cannot change to '"
                + activeServerGroup.getString(Constants.NAME) + "' - Check Server Group Exists"));
    } else {
        Client clientToUpdate = ClientService.getInstance().findClient(clientUUID, profileId);
        ServerRedirectService.getInstance().activateServerGroup(activeServerId, clientToUpdate.getId());
    }

    JSONArray enabledPaths = profileBackup.getJSONArray(Constants.ENABLED_PATHS);
    PathOverrideService pathOverrideService = PathOverrideService.getInstance();
    OverrideService overrideService = OverrideService.getInstance();

    for (int i = 0; i < enabledPaths.length(); i++) {
        JSONObject path = enabledPaths.getJSONObject(i);
        int pathId = pathOverrideService.getPathId(path.getString(Constants.PATH_NAME), profileId);
        // Set path to have request/response enabled as necessary
        try {
            if (path.getBoolean(Constants.REQUEST_ENABLED)) {
                pathOverrideService.setRequestEnabled(pathId, true, clientUUID);
            }

            if (path.getBoolean(Constants.RESPONSE_ENABLED)) {
                pathOverrideService.setResponseEnabled(pathId, true, clientUUID);
            }
        } catch (Exception e) {
            errors.put(formErrorJson("Path Error",
                    "Cannot update path: '" + path.getString(Constants.PATH_NAME) + "' - Check Path Exists"));
            continue;
        }

        JSONArray enabledOverrides = path.getJSONArray(Constants.ENABLED_ENDPOINTS);

        /**
         * 2 for loops to ensure overrides are added with correct priority
         * 1st loop is priority currently adding override to
         * 2nd loop is to find the override with matching priority in profile json
         */
        for (int j = 0; j < enabledOverrides.length(); j++) {
            for (int k = 0; k < enabledOverrides.length(); k++) {
                JSONObject override = enabledOverrides.getJSONObject(k);
                if (override.getInt(Constants.PRIORITY) != j) {
                    continue;
                }

                int overrideId;
                // Name of method that can be used by error message as necessary later
                String overrideNameForError = "";
                // Get the Id of the override
                try {
                    // If method information is null, then the override is a default override
                    if (override.get(Constants.METHOD_INFORMATION) != JSONObject.NULL) {
                        JSONObject methodInformation = override.getJSONObject(Constants.METHOD_INFORMATION);
                        overrideNameForError = methodInformation.getString(Constants.METHOD_NAME);
                        overrideId = overrideService.getOverrideIdForMethod(
                                methodInformation.getString(Constants.CLASS_NAME),
                                methodInformation.getString(Constants.METHOD_NAME));
                    } else {
                        overrideNameForError = "Default Override";
                        overrideId = override.getInt(Constants.OVERRIDE_ID);
                    }

                    // Enable override and set repeat number and arguments
                    overrideService.enableOverride(overrideId, pathId, clientUUID);
                    overrideService.updateRepeatNumber(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getInt(Constants.REPEAT_NUMBER), clientUUID);
                    overrideService.updateArguments(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getString(Constants.ARGUMENTS), clientUUID);
                } catch (Exception e) {
                    errors.put(formErrorJson("Override Error", "Cannot add/update override: '"
                            + overrideNameForError + "' - Check Override Exists"));
                    continue;
                }
            }
        }
    }

    // Throw exception if any errors occured
    if (errors.length() > 0) {
        throw new Exception(errors.toString());
    }
}

From source file:com.kakao.network.response.ResponseBody.java

private Object getOrThrow(String key) {
    Object v = null;//  ww w .  ja va  2  s  .com
    try {
        v = json.get(key);
    } catch (JSONException ignor) {
    }

    if (v == null) {
        throw new NoSuchElementException(key);
    }

    if (v == JSONObject.NULL) {
        return null;
    }
    return v;
}

From source file:org.archive.porky.JSON.java

/**
 * Convert the given Pig object into a JSON object, recursively
 * convert child objects as well.// w w  w .  j a  v  a 2 s . c  o m
 */
public static Object toJSON(Object o) throws JSONException, IOException {
    switch (DataType.findType(o)) {
    case DataType.NULL:
        return JSONObject.NULL;

    case DataType.BOOLEAN:
    case DataType.INTEGER:
    case DataType.LONG:
    case DataType.DOUBLE:
        return o;

    case DataType.FLOAT:
        return Double.valueOf(((Float) o).floatValue());

    case DataType.CHARARRAY:
        return o.toString();

    case DataType.MAP: {
        Map<String, Object> m = (Map<String, Object>) o;
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> e : m.entrySet()) {
            String key = e.getKey();
            Object value = toJSON(e.getValue());

            json.put(key, value);
        }
        return json;
    }

    case DataType.TUPLE: {
        JSONObject json = new JSONObject();

        Tuple t = (Tuple) o;
        for (int i = 0; i < t.size(); ++i) {
            Object value = toJSON(t.get(i));

            json.put("$" + i, value);
        }

        return json;
    }

    case DataType.BAG: {
        JSONArray values = new JSONArray();

        for (Tuple t : ((DataBag) o)) {
            switch (t.size()) {
            case 0:
                continue;

            case 1: {
                Object innerObject = toJSON(t.get(0));

                values.put(innerObject);
            }
                break;

            default:
                JSONArray innerList = new JSONArray();
                for (int i = 0; i < t.size(); ++i) {
                    Object innerObject = toJSON(t.get(i));

                    innerList.put(innerObject);
                }

                values.put(innerList);
                break;
            }

        }

        return values;
    }

    case DataType.BYTEARRAY:
        // FIXME?  What else can we do?  base-64 encoded string?
        System.err.println("Pig BYTEARRAY not supported for JSONStorage");
        return null;

    default:
        System.out.println("unknown type: " + DataType.findType(o) + " value: " + o.toString());
        return null;
    }
}

From source file:org.archive.porky.JSON.java

/**
 * Convert JSON object into a Pig object, recursively convert
 * children as well.// w  w w.j  a v  a  2s . c  o  m
 */
public static Object fromJSON(Object o) throws IOException, JSONException {
    if (o instanceof String || o instanceof Long || o instanceof Double || o instanceof Integer) {
        return o;
    } else if (JSONObject.NULL.equals(o)) {
        return null;
    } else if (o instanceof JSONObject) {
        JSONObject json = (JSONObject) o;

        Map<String, Object> map = new HashMap<String, Object>(json.length());

        // If getNames() returns null, then it's  an empty JSON object.
        String[] names = JSONObject.getNames(json);

        if (names == null)
            return map;

        for (String key : JSONObject.getNames(json)) {
            Object value = json.get(key);

            // Recurse the value
            map.put(key, fromJSON(value));
        }

        // Now, check to see if the map keys match the formula for
        // a Tuple, that is if they are: "$0", "$1", "$2", ...

        // First, peek to see if there is a "$0" key, if so, then 
        // start moving the map entries into a Tuple.
        if (map.containsKey("$0")) {
            Tuple tuple = TupleFactory.getInstance().newTuple(map.size());

            for (int i = 0; i < map.size(); i++) {
                // If any of the expected $N keys is not found, give
                // up and return the map.
                if (!map.containsKey("$" + i))
                    return map;

                tuple.set(i, map.get("$" + i));
            }

            return tuple;
        }

        return map;
    } else if (o instanceof JSONArray) {
        JSONArray json = (JSONArray) o;

        List<Tuple> tuples = new ArrayList<Tuple>(json.length());

        for (int i = 0; i < json.length(); i++) {
            tuples.add(TupleFactory.getInstance().newTuple(fromJSON(json.get(i))));
        }

        DataBag bag = BagFactory.getInstance().newDefaultBag(tuples);

        return bag;
    } else if (o instanceof Boolean) {
        // Since Pig doesn't have a true boolean data type, we map it to
        // String values "true" and "false".
        if (((Boolean) o).booleanValue()) {
            return "true";
        }
        return "false";
    } else {
        // FIXME: What to do here?
        throw new IOException("Unknown data-type serializing from JSON: " + o);
    }
}

From source file:edu.txstate.dmlab.clusteringwiki.sources.BaseCWSearchResultCol.java

/**
 * Create customized JSON representation of the object
 * @return//from w  w w. j ava 2s.com
 * @throws JSONException
 */
public JSONObject toJSON() throws JSONException {
    JSONObject j = new JSONObject();

    j.put("clusterKey", clusterKey);
    j.put("dataSourceKey", dataSourceKey);
    j.put("dataSourceName", dataSourceName);
    j.put("service", service);
    j.put("totalResults", totalResults);
    j.put("returnedCount", returnedCount);
    j.put("firstPosition", firstPosition);

    if (results != null) {
        JSONArray a = new JSONArray();
        for (ICWSearchResult r : results)
            a.put(r.toJSON());
        j.put("results", a);
    } else
        j.put("results", JSONObject.NULL);
    j.put("errors", errors);

    return j;
}