All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.json.JSONObject Maven / Gradle / Ivy

There is a newer version: 1.1.17
Show newest version
package com.json;

/*
 Copyright (c) 2002 JSON.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 The Software shall be used for Good, not Evil.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 */

import com.rt.core.util.RTUtil;

import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * A JSONObject is an unordered collection of name/value pairs. Its external
 * form is a string wrapped in curly braces with colons between the names and
 * values, and commas between the values and names. The internal form is an
 * object having get and opt methods for accessing the
 * values by name, and put methods for adding or replacing values
 * by name. The values can be any of these types: Boolean,
 * JSONArray, JSONObject, Number,
 * String, or the JSONObject.NULL object. A JSONObject
 * constructor can be used to convert an external form JSON text into an
 * internal form whose values can be retrieved with the get and
 * opt methods, or to convert values into a JSON text using the
 * put and toString methods. A get method
 * returns a value if one can be found, and throws an exception if one cannot be
 * found. An opt method returns a default value instead of throwing
 * an exception, and so is useful for obtaining optional values.
 *
 * @author JSON.org
 * @version 3
 */
public class JSONObject implements Map, Serializable {

    private static final long serialVersionUID = 1L;

    private static final String VALUE = "value";
    private static final String NULL_VALUE = "\"\"";

    /**
     * JSONObject.NULL is equivalent to the value that JavaScript calls null,
     * whilst Java's null is equivalent to the value that JavaScript calls
     * undefined.
     */
    private static final class Null {

        /**
         * There is only intended to be a single instance of the NULL object, so
         * the clone method returns itself.
         *
         * @return NULL.
         */
        @Override
        protected final Object clone() {
            return this;
        }

        /**
         * A Null object is equal to the null value and to itself.
         *
         * @param object An object to test for nullness.
         * @return true if the object parameter is the JSONObject.NULL object or
         * null.
         */
        @Override
        public boolean equals(Object object) {
            return object == null || object == this;
        }

        /**
         * Get the "null" string value.
         *
         * @return The string "null".
         */
        @Override
        public String toString() {
            return "";
        }
    }

    /**
     * The hash map where the JSONObject's properties are kept.
     */
    private Map jsonMap;

    /**
     * It is sometimes more convenient and less ambiguous to have a
     * NULL object than to use Java's null value.
     * JSONObject.NULL.equals(null) returns true.
     * JSONObject.NULL.toString() returns "null".
     */
    public static final Object NULL = new Null();

    /**
     * Construct an empty JSONObject.
     */
    public JSONObject() {
        this.jsonMap = new LinkedHashMap();
    }

    /**
     * Construct an empty JSONObject.
     * @param initialCapacity initialCapacity
     */
    public JSONObject(int initialCapacity) {
        this.jsonMap = new LinkedHashMap(initialCapacity);
    }

    /**
     * Construct a JSONObject from a JSONTokener.
     *
     * @param x A JSONTokener object containing the source string.
     * @throws JSONException If there is a syntax error in the source string.
     */
    public JSONObject(JSONTokener x) throws JSONException {
        this();
        char c;
        String key;

        if (x.nextClean() != '{') {
            throw x.syntaxError("A JSONObject text must begin with '{'");
        }
        for (; ; ) {
            c = x.nextClean();
            switch (c) {
                case 0:
                    throw x.syntaxError("A JSONObject text must end with '}'");
                case '}':
                    return;
                default:
                    x.back();
                    key = x.nextValue().toString();
            }

            /*
             * The key is followed by ':'. We will also tolerate '=' or '=>'.
             */

            c = x.nextClean();
            if (c == '=') {
                if (x.next() != '>') {
                    x.back();
                }
            } else if (c != ':') {
                throw x.syntaxError("Expected a ':' after a key");
            }
            put(key, x.nextValue());

            /*
             * Pairs are separated by ','. We will also tolerate ';'.
             */

            switch (x.nextClean()) {
                case ';':
                case ',':
                    if (x.nextClean() == '}') {
                        return;
                    }
                    x.back();
                    break;
                case '}':
                    return;
                default:
                    throw x.syntaxError("Expected a ',' or '}'");
            }
        }
    }

    /**
     * Construct a JSONObject from a Map.
     *
     * @param map A map object that can be used to initialize the contents of
     *            the JSONObject.
     */
    public JSONObject(Map map) {
        if (map == null) {
            this.jsonMap = new LinkedHashMap();
        } else {
            this.jsonMap = map;
        }
    }

    /**
     * Construct a JSONObject from an Object, using reflection to find the
     * public members. The resulting JSONObject's keys will be the strings from
     * the names array, and the values will be the field values associated with
     * those keys in the object. If a key is not found or not visible, then it
     * will not be copied into the new JSONObject.
     *
     * @param object An object that has fields that should be used to make a
     *               JSONObject.
     * @param names  An array of strings, the names of the fields to be used from
     *               the object.
     */
    public JSONObject(Object object, String names[]) {
        this();
        Class c = object.getClass();
        for (String s : names) {
            try {
                String name = s;
                Field field = c.getField(name);
                Object value = field.get(object);
                this.put(name, value);
            } catch (Exception e) {
                /* forget about it */
            }
        }
    }

    /**
     * Construct a JSONObject from a string. This is the most commonly used
     * JSONObject constructor.
     *
     * @param string A string beginning with { (left
     *               brace) and ending with }
     *                (right brace).
     * @throws JSONException If there is a syntax error in the source string.
     */
    public JSONObject(String string) throws JSONException {
        this(new JSONTokener(string));
    }

    /**
     * Accumulate values under a key. It is similar to the put method except
     * that if there is already an object stored under the key then a JSONArray
     * is stored under the key to hold all of the accumulated values. If there
     * is already a JSONArray, then the new value is appended to it. In
     * contrast, the put method replaces the previous value.
     *
     * @param key   A key string.
     * @param value An object to be accumulated under the key.
     * @return this.
     * @throws JSONException If the value is an invalid number or if the key is null.
     */
    public JSONObject accumulate(String key, Object value) throws JSONException {
        // testValidity(value);
        Object o = opt(key);
        if (o == null) {
            put(key, value instanceof JSONArray ? new JSONArray().put(value)
                    : value);
        } else if (o instanceof JSONArray) {
            ((JSONArray) o).put(value);
        } else {
            put(key, new JSONArray().put(o).put(value));
        }
        return this;
    }

    /**
     * Append values to the array under a key. If the key does not exist in the
     * JSONObject, then the key is put in the JSONObject with its value being a
     * JSONArray containing the value parameter. If the key was already
     * associated with a JSONArray, then the value parameter is appended to it.
     *
     * @param key   A key string.
     * @param value An object to be accumulated under the key.
     * @return this.
     * @throws JSONException If the key is null or if the current value associated with
     *                       the key is not a JSONArray.
     */
    public JSONObject append(String key, Object value) throws JSONException {
        // testValidity(value);
        Object o = opt(key);
        if (o == null) {
            put(key, new JSONArray().put(value));
        } else if (o instanceof JSONArray) {
            put(key, ((JSONArray) o).put(value));
        } else {
            throw new JSONException("JSONObject[" + key
                    + "] is not a JSONArray.");
        }
        return this;
    }

    /**
     * 获取当前对象中所有内容
     *
     * @return Map
     */
    public Map getJSONContext() {
        return this.jsonMap;
    }

    /**
     * 设置内容
     *
     * @param map map
     */
    public void setJSONContext(Map map) {
        this.jsonMap = map;
    }

    /**
     * id
     *
     * @return String
     */
    public String getId() {
        return getString("id");
    }

    /**
     * id
     *
     * @param id id
     */
    public void setId(String id) {
        put("id", id);
    }

    /**
     * Get the value object associated with a key.
     *
     * @param key A key string.
     * @return The object associated with the key.
     */
    public Object get(String key) {
        return opt(key);
    }

    /**
     * 获取指定数据
     * 父类get(key)方法增强,自动转换.
     *
     * @param key key
     * @param  object
     * @return T object
     */
    public  T getObject(String key) {
        return (T) get(key);
    }

    /**
     * build List - JSONArray
     * 先获取第二个参数值,如果没有,从第一个参数构造.
     *
     * @param src src
     * @param key key
     * @param putIn putIn
     * @return Array
     */
    public JSONArray getJSONArray(String key, String src, boolean putIn) {
        JSONArray list = getJSONArray(key);
        if (list == null) {
            list = getJSONArray(src);
            if (putIn) {
                put(key, list);
            }
        }
        if (list == null) {
            list = new JSONArray();
            if (putIn) {
                put(key, list);
            }
        }
        return list;
    }

    /**
     * 获取参数,如果没有,构造一个新的,放入列表.
     *
     * @param key key
     * @param putIn putIn
     * @return Array
     */
    public JSONArray getJSONArray(String key, boolean putIn) {
        JSONArray list = getJSONArray(key);
        if (list == null) {
            list = new JSONArray();
            if (putIn) {
                put(key, list);
            }
        }
        return list;
    }

    /**
     * Get the JSONArray value associated with a key.
     *
     * @param key A key string.
     * @return A JSONArray which is the value.
     */
    public JSONArray getJSONArray(String key) {
        if (isNull(key)) {
            return null;
        }
        Object o = get(key);
        if (o instanceof JSONArray) {
            return (JSONArray) o;
        } else if (o instanceof String) {
            try {
                return new JSONArray(o.toString());
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * build JSONObject - JSONObject
     * 先获取第二个参数值,如果没有,从第一个参数构造.
     *
     * @param src src
     * @param key key
     * @param putIn putIn
     * @return JSONObject
     */
    public JSONObject getJSONObject(String key, String src, boolean putIn) {
        JSONObject map = getJSONObject(key);
        if (map == null) {
            map = getJSONObject(src);
            if (putIn) {
                put(key, map);
            }
        }
        if (map == null) {
            map = new JSONObject();
            if (putIn) {
                put(key, map);
            }
        }
        return map;
    }

    /**
     * 获取参数,如果没有,构造一个新的,放入列表.
     *
     * @param key key
     * @param putIn putIn
     * @return JSONObject
     */
    public JSONObject getJSONObject(String key, boolean putIn) {
        JSONObject map = getJSONObject(key);
        if (map == null) {
            map = new JSONObject();
            if (putIn) {
                put(key, map);
            }
        }
        return map;
    }

    /**
     * Get the JSONObject value associated with a key.
     *
     * @param key A key string.
     * @return A JSONObject which is the value.
     */
    public JSONObject getJSONObject(String key) {
        if (isNull(key)) {
            return null;
        }
        Object o = get(key);
        if (o instanceof JSONObject) {
            return (JSONObject) o;
        } else if (o instanceof String) {
            try {
                return new JSONObject(o.toString());
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * Get the string associated with a key.
     *
     * @param key A key string.
     * @return Serializable A string which is the value.
     */
    public Serializable getSerializable(String key) {
        return getObject(key);
    }

    /**
     * Get the string associated with a key.
     *
     * @param key A key string.
     * @return A string which is the value.
     */
    public String getString(String key) {
        return RTUtil.val(get(key));
    }

    /**
     * Get the string associated with a key.
     *
     * @param key          A key string.
     * @param defaultValue Value string.
     * @return A string which is the value.
     */
    public String getString(String key, String defaultValue) {
        return RTUtil.val(get(key), defaultValue);
    }

    /**
     * Get boolean value
     *
     * @param key key
     * @return boolean
     */
    public boolean getBoolean(String key) {
        return RTUtil.toboolean(get(key));
    }

    /**
     * Get BigDecimal value
     *
     * @param key key
     * @return BigDecimal
     */
    public BigDecimal getBigDecimal(String key) {
        return RTUtil.toBigDecimal(get(key));
    }

    /**
     * Get double value
     *
     * @param key key
     * @return double
     */
    public double getdouble(String key) {
        return RTUtil.todouble(get(key));
    }

    /**
     * Get double value
     *
     * @param key key
     * @param defaultValue defaultValue
     * @return double
     */
    public double getdouble(String key, double defaultValue) {
        return RTUtil.todouble(get(key), defaultValue);
    }

    /**
     * Get Long value
     *
     * @param key key
     * @return long
     */
    public long getlong(String key) {
        return RTUtil.tolong(get(key));
    }

    /**
     * Get Long value
     *
     * @param key key
     * @param defaultValue defaultValue
     * @return long
     */
    public long getlong(String key, long defaultValue) {
        return RTUtil.tolong(get(key), defaultValue);
    }

    /**
     * Get Long value
     *
     * @param key key
     * @return long
     */
    public Long getLong(String key) {
        return RTUtil.toLong(get(key));
    }

    /**
     * Get Long value
     *
     * @param key key
     * @param defaultValue defaultValue
     * @return Long
     */
    public Long getLong(String key, long defaultValue) {
        return RTUtil.toLong(get(key), defaultValue);
    }

    /**
     * Get int value
     *
     * @param key key
     * @return int int
     */
    public int getInt(String key) {
        return RTUtil.toInt(get(key));
    }

    /**
     * Get int value
     *
     * @param key key
     * @param defaultValue defaultValue
     * @return int int
     */
    public int getInt(String key, int defaultValue) {
        return RTUtil.toInt(get(key), defaultValue);
    }

    /**
     * Get int value
     *
     * @param key key
     * @return int
     */
    public Integer getInteger(String key) {
        return RTUtil.toInteger(get(key));
    }

    /**
     * Get int value
     *
     * @param key key
     * @param defaultValue defaultValue
     * @return int
     */
    public Integer getInteger(String key, int defaultValue) {
        return RTUtil.toInteger(get(key), defaultValue);
    }

    /**
     * Determine if the JSONObject contains a specific key.
     *
     * @param key A key string.
     * @return true if the key exists in the JSONObject.
     */
    public boolean has(String key) {
        return this.jsonMap.containsKey(key);
    }

    /**
     * Determine if the value associated with the key is null or if there is no
     * value.
     *
     * @param key A key string.
     * @return true if there is no value associated with the key or if the value
     * is the JSONObject.NULL object.
     */
    public boolean isNull(String key) {
        return JSONObject.NULL.equals(opt(key));
    }

    /**
     * Get an enumeration of the keys of the JSONObject.
     *
     * @return An iterator of the keys.
     */
    public Iterator keys() {
        return this.jsonMap.keySet().iterator();
    }

    /**
     * Get the number of keys stored in the JSONObject.
     *
     * @return The number of keys in the JSONObject.
     */
    public int length() {
        return this.jsonMap.size();
    }

    /**
     * Produce a JSONArray containing the names of the elements of this
     * JSONObject.
     *
     * @return A JSONArray containing the key strings, or null if the JSONObject
     * is empty.
     */
    public JSONArray names() {
        JSONArray ja = new JSONArray();
        Iterator keys = keys();
        while (keys.hasNext()) {
            ja.put(keys.next());
        }
        return ja.length() == 0 ? null : ja;
    }

    /**
     * Produce a string from a Number.
     *
     * @param n A Number
     * @return A String.
     * @throws JSONException If n is a non-finite number.
     */
    static public String numberToString(Number n) throws JSONException {
        if (n == null) {
            throw new JSONException("Null pointer");
        }
        // testValidity(n);
        // BigDecimal to String
        if (n instanceof BigDecimal) {
            String s = ((BigDecimal) n).toPlainString();
            StringBuffer sb = new StringBuffer(s.length() + 4);
            sb.append('"');
            sb.append(s);
            sb.append('"');
            return sb.toString();
        }
        // Shave off trailing zeros and decimal point, if possible.

        String s = n.toString();
        if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
            while (s.endsWith("0")) {
                s = s.substring(0, s.length() - 1);
            }
            if (s.endsWith(".")) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }

    /**
     * Get an optional value associated with a key.
     *
     * @param key A key string.
     * @return An object which is the value, or null if there is no value.
     */
    private Object opt(String key) {
        return key == null ? null : this.jsonMap.get(key);
    }

    /**
     * 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.
     *
     * @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, Long,
     *              String, or the JSONObject.NULL object.
     * @return this. or if the key is null.
     */
    public Object put(String key, Object value) {
        this.jsonMap.put(key, value);
        return this;
    }

    /**
     * Produce a string in double quotes with backslash sequences in all the
     * right places. A backslash will be inserted within, allowing JSON text
     * to be delivered in HTML. In JSON text, a string cannot contain a control
     * character or an unescaped quote or backslash.
     *
     * @param string A String
     * @return A String correctly formatted for insertion in a JSON text.
     */
    public static String quote(String string) {
        if (string == null || string.length() == 0) {
            return NULL_VALUE;
        }

        char b;
        char c = 0;
        int i;
        int len = string.length();
        StringBuffer sb = new StringBuffer(len + 4);
        String t;

        sb.append('"');
        for (i = 0; i < len; i += 1) {
            b = c;
            c = string.charAt(i);
            switch (c) {
                case '\\':
                case '"':
                    sb.append('\\');
                    sb.append(c);
                    break;
                case '/':
                    if (b == '<') {
                        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 < ' ' || (c >= '\u0080' && c < '\u00a0')
                            || (c >= '\u2000' && c < '\u2100')) {
                        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 this.jsonMap.remove(key);
    }

    /**
     * Clear all attribute.
     */
    @Override
    public void clear() {
        if (this.jsonMap != null) {
            this.jsonMap.clear();
        }
    }

    /**
     * Throw an exception if the object is an NaN or infinite number.
     *
     * @param o The object to test.
     * @throws JSONException If o is a non-finite number.
     */
    static void testValidity(Object o) {
        if (o != null) {
            if (o instanceof Double) {
                if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
                }
            } else if (o instanceof Float) {
                if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
                }
            }
        }
    }

    public JSONObject copy() {
        try {
            return new JSONObject(this.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Make a JSON text of this JSONObject. For compactness, no whitespace is
     * added. If this would not result in a syntactically correct JSON text,
     * then null will be returned instead.
     * 

* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable representation * of the object, beginning with { (left * brace) and ending with } (right * brace). */ @Override public String toString() { try { Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.jsonMap.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. *

* 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 { (left * brace) and ending with } (right * brace). */ public String toString(int indentFactor) { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. *

* 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 { (left * brace) and ending with } (right * brace). */ String toString(int indentFactor, int indent) { int i; int n = length(); if (n == 0) { return "{}"; } Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; if (n == 1) { o = keys.next(); sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.jsonMap.get(o), indentFactor, indent)); } else { while (keys.hasNext()) { o = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (i = 0; i < newindent; i += 1) { sb.append(' '); } sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.jsonMap.get(o), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce the * JSON text. The method is required to produce a strictly conforming text. * If the object does not contain a toJSONString method (which is the most * common case), then a text will be produced by the rules. *

* Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @return JSON String * @throws JSONException JSONException */ static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return NULL_VALUE; } if (value instanceof JSONString) { Object o; try { o = ((JSONString) value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (o instanceof String) { return (String) o; } throw new JSONException("Bad value from toJSONString: " + o); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value.getClass().isArray()) { Object[] valueArray = (Object[]) value; if (valueArray == null || valueArray.length == 0) { return ""; } JSONArray array = new JSONArray(); for (int i = 0; i < valueArray.length; i++) { array.put(valueArray[i]); } return array.toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. *

* Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @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 { (left * brace) and ending with } (right * brace). */ static String valueToString(Object value, int indentFactor, int indent) { if (value == null || value.equals(null)) { return NULL_VALUE; } try { if (value instanceof JSONString) { Object o = ((JSONString) value).toJSONString(); if (o instanceof String) { return (String) o; } } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject) value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray) value).toString(indentFactor, indent); } if (value.getClass().isArray()) { Object[] valueArray = (Object[]) value; if (valueArray == null || valueArray.length == 0) { return ""; } JSONArray array = new JSONArray(); for (int i = 0; i < valueArray.length; i++) { array.put(valueArray[i]); } return array.toString(indentFactor, indent); } } catch (Exception e) { return NULL_VALUE; } return quote(value.toString()); } /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. * * @param writer writer * @return The writer. * @throws JSONException JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; Iterator keys = keys(); writer.write('{'); while (keys.hasNext()) { if (b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.jsonMap.get(k); if (v instanceof JSONObject) { ((JSONObject) v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray) v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch (IOException e) { throw new JSONException(e); } } @Override public boolean containsKey(Object key) { return jsonMap.containsKey(key); } @Override public boolean containsValue(Object value) { return jsonMap.containsValue(value); } @Override public Set entrySet() { return jsonMap.entrySet(); } @Override public Object get(Object key) { return jsonMap.get(key); } @Override public boolean isEmpty() { return jsonMap.isEmpty(); } @Override public Set keySet() { return jsonMap.keySet(); } @Override public Object put(Object key, Object value) { return jsonMap.put(key, value); } @Override public void putAll(Map m) { jsonMap.putAll(m); } @Override public Object remove(Object key) { return jsonMap.remove(key); } @Override public int size() { return jsonMap.size(); } @Override public Collection values() { return jsonMap.values(); } /** * 值 * * @return the value */ public Object getValue() { return get(VALUE); } /** * string值 * * @return the value */ public String getValueToString() { return getString(VALUE); } /** * 值 * * @param value the value to set */ public void setValue(Object value) { put(VALUE, value); } /** * int值 * * @return the value */ public int getValueToInt() { return getInt(VALUE); } /** * double值 * * @return the value */ public double getValueTodouble() { return getdouble(VALUE); } /** * int值 * * @return the value */ public int getValueToint() { return getInt(VALUE); } /** * long值 * * @return the value */ public long getValueTolong() { return getlong(VALUE); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy