⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jsonobject.java

📁 《AJAX基础》一书的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    }    /**     * Get an optional value associated with a key.     * @exception NullPointerException  The key must not be null.     * @param key   A key string.     * @return      An object which is the value, or null if there is no value.     */    public Object opt(String key) throws NullPointerException {        if (key == null) {            throw new NullPointerException("Null key");        }        return myHashMap.get(key);    }    /**     * Get an optional boolean associated with a key.     * It returns false if there is no such key, or if the value is not     * Boolean.TRUE or the String "true".     *     * @param key   A key string.     * @return      The truth.     */    public boolean optBoolean(String key) {        return optBoolean(key, false);    }    /**     * Get an optional boolean associated with a key.     * It returns the defaultValue if there is no such key, or if it is not     * a Boolean or the String "true" or "false" (case insensitive).     *     * @param key              A key string.     * @param defaultValue     The default.     * @return      The truth.     */    public boolean optBoolean(String key, boolean defaultValue) {        Object o = opt(key);        if (o != null) {            if (o == Boolean.FALSE || 					(o instanceof String && 					((String)o).equalsIgnoreCase("false"))) {                return false;            } else if (o == Boolean.TRUE || 					(o instanceof String && 					((String)o).equalsIgnoreCase("true"))) {                return true;            }        }        return defaultValue;    }    /**     * Get an optional double associated with a key,     * or NaN if there is no such key or if its value is not a number.     * If the value is a string, an attempt will be made to evaluate it as     * a number.     *     * @param key   A string which is the key.     * @return      An object which is the value.     */    public double optDouble(String key)  {        return optDouble(key, Double.NaN);    }    /**     * Get an optional double associated with a key, or the     * defaultValue if there is no such key or if its value is not a number.     * If the value is a string, an attempt will be made to evaluate it as     * a number.     *     * @param key   A key string.     * @param defaultValue     The default.     * @return      An object which is the value.     */    public double optDouble(String key, double defaultValue)  {        Object o = opt(key);        if (o != null) {            if (o instanceof Number) {                return ((Number)o).doubleValue();            }            try {                return new Double((String)o).doubleValue();            }            catch (Exception e) {            }        }        return defaultValue;    }    /**     * Get an optional int value associated with a key,     * or zero if there is no such key or if the value is not a number.     * If the value is a string, an attempt will be made to evaluate it as     * a number.     *     * @param key   A key string.     * @return      An object which is the value.     */    public int optInt(String key) {        return optInt(key, 0);    }    /**     * Get an optional int value associated with a key,     * or the default if there is no such key or if the value is not a number.     * If the value is a string, an attempt will be made to evaluate it as     * a number.     *     * @param key   A key string.     * @param defaultValue     The default.     * @return      An object which is the value.     */    public int optInt(String key, int defaultValue) {        Object o = opt(key);        if (o != null) {            if (o instanceof Number) {                return ((Number)o).intValue();            }            try {                return Integer.parseInt((String)o);            } catch (Exception e) {            }        }        return defaultValue;    }    /**     * Get an optional JSONArray associated with a key.     * It returns null if there is no such key, or if its value is not a     * JSONArray.     *     * @param key   A key string.     * @return      A JSONArray which is the value.     */    public JSONArray optJSONArray(String key) {        Object o = opt(key);        if (o instanceof JSONArray) {            return (JSONArray) o;        }        return null;    }    /**     * Get an optional JSONObject associated with a key.     * It returns null if there is no such key, or if its value is not a     * JSONObject.     *     * @param key   A key string.     * @return      A JSONObject which is the value.     */    public JSONObject optJSONObject(String key) {        Object o = opt(key);        if (o instanceof JSONObject) {            return (JSONObject)o;        }        return null;    }    /**     * Get an optional string associated with a key.     * It returns an empty string if there is no such key. If the value is not     * a string and is not null, then it is coverted to a string.     *     * @param key   A key string.     * @return      A string which is the value.     */    public String optString(String key) {        return optString(key, "");    }    /**     * Get an optional string associated with a key.     * It returns the defaultValue if there is no such key.     *     * @param key   A key string.     * @param defaultValue     The default.     * @return      A string which is the value.     */    public String optString(String key, String defaultValue) {        Object o = opt(key);        if (o != null) {            return o.toString();        }        return defaultValue;    }    /**     * Put a key/boolean pair in the JSONObject.     *     * @param key   A key string.     * @param value A boolean which is the value.     * @return this.     */    public JSONObject put(String key, boolean value) {        put(key, new Boolean(value));        return this;    }    /**     * Put a key/double pair in the JSONObject.     *     * @param key   A key string.     * @param value A double which is the value.     * @return this.     */    public JSONObject put(String key, double value) {        put(key, new Double(value));        return this;    }    /**     * Put a key/int pair in the JSONObject.     *     * @param key   A key string.     * @param value An int which is the value.     * @return this.     */    public JSONObject put(String key, int value) {        put(key, new Integer(value));        return this;    }    /**     * Put a key/value pair in the JSONObject. If the value is null,     * then the key will be removed from the JSONObject if it is present.     * @exception NullPointerException The key must be non-null.     * @param key   A key string.     * @param value An object which is the value. It should be of one of these     *  types: Boolean, Double, Integer, JSONArray, JSONObject, String, or the     *  JSONObject.NULL object.     * @return this.     */    public JSONObject put(String key, Object value) throws NullPointerException {        if (key == null) {            throw new NullPointerException("Null key.");        }        if (value != null) {            myHashMap.put(key, value);        } else {            remove(key);        }        return this;    }    /**     * Put a key/value pair in the JSONObject, but only if the     * value is non-null.     * @exception NullPointerException The key must be non-null.     * @param key   A key string.     * @param value An object which is the value. It should be of one of these     *  types: Boolean, Double, Integer, JSONArray, JSONObject, String, or the     *  JSONObject.NULL object.     * @return this.     */    public JSONObject putOpt(String key, Object value) throws NullPointerException {        if (value != null) {            put(key, value);        }        return this;    }    /**     * Produce a string in double quotes with backslash sequences in all the     * right places.     * @param string A String     * @return  A String correctly formatted for insertion in a JSON message.     */    public static String quote(String string) {        if (string == null || string.length() == 0) {            return "\"\"";        }        char         c;        int          i;        int          len = string.length();        StringBuffer sb = new StringBuffer(len + 4);        String       t;        sb.append('"');        for (i = 0; i < len; i += 1) {            c = string.charAt(i);            switch (c) {            case '\\':            case '"':            case '/':                sb.append('\\');                sb.append(c);                break;            case '\b':                sb.append("\\b");                break;            case '\t':                sb.append("\\t");                break;            case '\n':                sb.append("\\n");                break;            case '\f':                sb.append("\\f");                break;            case '\r':                sb.append("\\r");                break;            default:                if (c < ' ') {                    t = "000" + Integer.toHexString(c);                    sb.append("\\u" + t.substring(t.length() - 4));                } else {                    sb.append(c);                }            }        }        sb.append('"');        return sb.toString();    }    /**     * Remove a name and its value, if present.     * @param key The name to be removed.     * @return The value that was associated with the name,     * or null if there was no value.     */    public Object remove(String key) {        return myHashMap.remove(key);    }    /**     * Produce a JSONArray containing the values of the members of this     * JSONObject.     * @param names A JSONArray containing a list of key strings. This     * determines the sequence of the values in the result.     * @return A JSONArray of values.     */    public JSONArray toJSONArray(JSONArray names) {        if (names == null || names.length() == 0) {            return null;        }        JSONArray ja = new JSONArray();        for (int i = 0; i < names.length(); i += 1) {            ja.put(this.opt(names.getString(i)));        }        return ja;    }    /**     * Make an JSON external form string of this JSONObject. For compactness, no     * unnecessary whitespace is added.     * <p>     * Warning: This method assumes that the data structure is acyclical.     *     * @return a printable, displayable, portable, transmittable     *  representation of the object, beginning      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending      *  with <code>}</code>&nbsp;<small>(right brace)</small>.     */    public String toString() {        Iterator     keys = keys();        Object       o = null;        String       s;        StringBuffer sb = new StringBuffer();        sb.append('{');        while (keys.hasNext()) {            if (o != null) {                sb.append(',');            }            s = keys.next().toString();            o = myHashMap.get(s);            if (o != null) {                sb.append(quote(s));                sb.append(':');                if (o instanceof String) {                    sb.append(quote((String)o));                } else if (o instanceof Number) {                    sb.append(numberToString((Number)o));                } else {                    sb.append(o.toString());                }            }        }        sb.append('}');        return sb.toString();    }    /**     * Make a prettyprinted JSON external form string of this JSONObject.     * <p>     * Warning: This method assumes that the data structure is acyclical.     * @param indentFactor The number of spaces to add to each level of     *  indentation.     * @return a printable, displayable, portable, transmittable     *  representation of the object, beginning     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending      *  with <code>}</code>&nbsp;<small>(right brace)</small>.     */    public String toString(int indentFactor) {        return toString(indentFactor, 0);    }    /**     * Make a prettyprinted JSON string of this JSONObject.     * <p>     * Warning: This method assumes that the data structure is acyclical.     * @param indentFactor The number of spaces to add to each level of     *  indentation.     * @param indent The indentation of the top level.     * @return a printable, displayable, transmittable     *  representation of the object, beginning      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending      *  with <code>}</code>&nbsp;<small>(right brace)</small>.     */    String toString(int indentFactor, int indent) {        int          i;        Iterator     keys = keys();        String       pad = "";        StringBuffer sb = new StringBuffer();        int newindent = indent + indentFactor;        for (i = 0; i < newindent; i += 1) {            pad += ' ';        }        sb.append('{');        while (keys.hasNext()) {            String s = keys.next().toString();            Object o = myHashMap.get(s);            if (o != null) {                if (sb.length() > 1) {                    sb.append(",\n");                } else {					sb.append('\n');                }                sb.append(pad);                sb.append(quote(s));                sb.append(": ");                if (o instanceof String) {                    sb.append(quote((String)o));                } else if (o instanceof Number) {                    sb.append(numberToString((Number) o));                } else if (o instanceof JSONObject) {                    sb.append(((JSONObject)o).toString(indentFactor, newindent));                } else if (o instanceof JSONArray) {                    sb.append(((JSONArray)o).toString(indentFactor, newindent));                } else {                    sb.append(o.toString());                }            }        }		if (sb.length() > 1) {			sb.append('\n');	        for (i = 0; i < indent; i += 1) {				sb.append(' ');	        }		}        sb.append('}');        return sb.toString();    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -