Class JSONObject


  • public class JSONObject
    extends java.lang.Object
    A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles, or the special sentinel value NULL.

    This class provides methods to store and retrieve values by their associated names, with support for type coercion when accessing values. It also includes functionality for converting the object to and from JSON formatted strings.

    Example Usage

    
     // Creating a new JSONObject and adding key-value pairs
     JSONObject obj = new JSONObject();
     obj.put("name", "Alice");
     obj.put("age", 30);
    
     // Retrieving values
     String name = obj.getString("name"); // returns "Alice"
     int age = obj.getInt("age");         // returns 30
    
     // Using opt methods to provide default values
     boolean isMember = obj.optBoolean("isMember", false); // returns false if not present
    
     // Converting to JSON string
     String jsonStr = obj.toString(); // {"name":"Alice","age":30}
    
     // Parsing from JSON string
     String inputJson = "{\"city\":\"New York\",\"population\":8175133}";
     JSONObject parsedObj = new JSONObject(inputJson);
     String city = parsedObj.getString("city"); // "New York"
     
    See Also:
    JSONArray, JSONTokener
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.Object NULL
      A sentinel value used to explicitly define a name with no value.
    • Constructor Summary

      Constructors 
      Constructor Description
      JSONObject()
      Creates a JSONObject with no name/value mappings.
      JSONObject​(JSONObject copyFrom, java.lang.String[] names)
      Creates a new JSONObject by copying mappings for the listed names from the given object.
      JSONObject​(JSONTokener readFrom)
      Creates a new JSONObject with name/value mappings from the next object in the tokener.
      JSONObject​(java.lang.String json)
      Creates a new JSONObject with name/value mappings from the JSON string.
      JSONObject​(java.util.Map copyFrom)
      Creates a new JSONObject by copying all name/value mappings from the given map.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      JSONObject accumulate​(java.lang.String name, java.lang.Object value)
      Appends value to the array already mapped to name.
      boolean equals​(java.lang.Object o)  
      java.lang.Object get​(java.lang.String name)
      Returns the value mapped by name.
      boolean getBoolean​(java.lang.String name)
      Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean.
      double getDouble​(java.lang.String name)
      Returns the value mapped by name if it exists and is a double or can be coerced to a double.
      int getInt​(java.lang.String name)
      Returns the value mapped by name if it exists and is an int or can be coerced to an int.
      JSONArray getJSONArray​(java.lang.String name)
      Returns the value mapped by name if it exists and is a JSONArray.
      JSONObject getJSONObject​(java.lang.String name)
      Returns the value mapped by name if it exists and is a JSONObject.
      long getLong​(java.lang.String name)
      Returns the value mapped by name if it exists and is a long or can be coerced to a long.
      java.lang.String getString​(java.lang.String name)
      Returns the value mapped by name if it exists, coercing it if necessary.
      boolean has​(java.lang.String name)
      Returns true if this object has a mapping for name.
      int hashCode()  
      boolean isNull​(java.lang.String name)
      Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
      java.util.Iterator keys()
      Returns an iterator of the String names in this object.
      int length()
      Returns the number of name/value mappings in this object.
      JSONArray names()
      Returns an array containing the string names in this object.
      static java.lang.String numberToString​(java.lang.Number number)
      Encodes the number as a JSON string.
      java.lang.Object opt​(java.lang.String name)
      Returns the value mapped by name, or null if no such mapping exists.
      boolean optBoolean​(java.lang.String name)
      Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean.
      boolean optBoolean​(java.lang.String name, boolean fallback)
      Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean.
      double optDouble​(java.lang.String name)
      Returns the value mapped by name if it exists and is a double or can be coerced to a double.
      double optDouble​(java.lang.String name, double fallback)
      Returns the value mapped by name if it exists and is a double or can be coerced to a double.
      int optInt​(java.lang.String name)
      Returns the value mapped by name if it exists and is an int or can be coerced to an int.
      int optInt​(java.lang.String name, int fallback)
      Returns the value mapped by name if it exists and is an int or can be coerced to an int.
      JSONArray optJSONArray​(java.lang.String name)
      Returns the value mapped by name if it exists and is a JSONArray.
      JSONObject optJSONObject​(java.lang.String name)
      Returns the value mapped by name if it exists and is a JSONObject.
      long optLong​(java.lang.String name)
      Returns the value mapped by name if it exists and is a long or can be coerced to a long.
      long optLong​(java.lang.String name, long fallback)
      Returns the value mapped by name if it exists and is a long or can be coerced to a long.
      java.lang.String optString​(java.lang.String name)
      Returns the value mapped by name if it exists, coercing it if necessary.
      java.lang.String optString​(java.lang.String name, java.lang.String fallback)
      Returns the value mapped by name if it exists, coercing it if necessary.
      JSONObject put​(java.lang.String name, boolean value)
      Maps name to value, clobbering any existing name/value mapping with the same name.
      JSONObject put​(java.lang.String name, double value)
      Maps name to value, clobbering any existing name/value mapping with the same name.
      JSONObject put​(java.lang.String name, int value)
      Maps name to value, clobbering any existing name/value mapping with the same name.
      JSONObject put​(java.lang.String name, long value)
      Maps name to value, clobbering any existing name/value mapping with the same name.
      JSONObject put​(java.lang.String name, java.lang.Object value)
      Maps name to value, clobbering any existing name/value mapping with the same name.
      JSONObject putOpt​(java.lang.String name, java.lang.Object value)
      Equivalent to put(name, value) when both parameters are non-null; does nothing otherwise.
      static java.lang.String quote​(java.lang.String data)
      Encodes data as a JSON string.
      java.lang.Object remove​(java.lang.String name)
      Removes the named mapping if it exists; does nothing otherwise.
      JSONArray toJSONArray​(JSONArray names)
      Returns an array with the values corresponding to names.
      java.lang.String toString()
      Encodes this object as a compact JSON string, such as:
      java.lang.String toString​(int indentSpaces)
      Encodes this object as a human-readable JSON string for debugging, such as:
      static java.lang.Object wrap​(java.lang.Object o)
      Wraps the given object if necessary.
      • Methods inherited from class java.lang.Object

        clone, finalize, getClass, notify, notifyAll, wait, wait, wait
    • Field Detail

      • NULL

        public static final java.lang.Object NULL
        A sentinel value used to explicitly define a name with no value. Unlike null, names with this value:

        This value violates the general contract of Object.equals(java.lang.Object) by returning true when compared to null. Its toString() method returns "null".

    • Constructor Detail

      • JSONObject

        public JSONObject()
        Creates a JSONObject with no name/value mappings.
      • JSONObject

        public JSONObject​(java.util.Map copyFrom)
        Creates a new JSONObject by copying all name/value mappings from the given map.
        Parameters:
        copyFrom - a map whose keys are of type String and whose values are of supported types.
        Throws:
        java.lang.NullPointerException - if any of the map's keys are null.
      • JSONObject

        public JSONObject​(JSONTokener readFrom)
                   throws JSONException
        Creates a new JSONObject with name/value mappings from the next object in the tokener.
        Parameters:
        readFrom - a tokener whose nextValue() method will yield a JSONObject.
        Throws:
        JSONException - if the parse fails or doesn't yield a JSONObject.
      • JSONObject

        public JSONObject​(java.lang.String json)
                   throws JSONException
        Creates a new JSONObject with name/value mappings from the JSON string.
        Parameters:
        json - a JSON-encoded string containing an object.
        Throws:
        JSONException - if the parse fails or doesn't yield a JSONObject.
      • JSONObject

        public JSONObject​(JSONObject copyFrom,
                          java.lang.String[] names)
                   throws JSONException
        Creates a new JSONObject by copying mappings for the listed names from the given object. Names that aren't present in copyFrom will be skipped.
        Parameters:
        copyFrom - the source
        names - the property names
        Throws:
        JSONException - if an error occurs
    • Method Detail

      • length

        public int length()
        Returns the number of name/value mappings in this object.
        Returns:
        the number of name/value mappings in this object
      • put

        public JSONObject put​(java.lang.String name,
                              boolean value)
                       throws JSONException
        Maps name to value, clobbering any existing name/value mapping with the same name.
        Parameters:
        name - the name of the property
        value - the value of the property
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • put

        public JSONObject put​(java.lang.String name,
                              double value)
                       throws JSONException
        Maps name to value, clobbering any existing name/value mapping with the same name.
        Parameters:
        name - the name of the property
        value - a finite value. May not be NaNs or infinities.
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • put

        public JSONObject put​(java.lang.String name,
                              int value)
                       throws JSONException
        Maps name to value, clobbering any existing name/value mapping with the same name.
        Parameters:
        name - the name of the property
        value - the value of the property
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • put

        public JSONObject put​(java.lang.String name,
                              long value)
                       throws JSONException
        Maps name to value, clobbering any existing name/value mapping with the same name.
        Parameters:
        name - the name of the property
        value - the value of the property
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • put

        public JSONObject put​(java.lang.String name,
                              java.lang.Object value)
                       throws JSONException
        Maps name to value, clobbering any existing name/value mapping with the same name. If the value is null, any existing mapping for name is removed.
        Parameters:
        name - the name of the property
        value - a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities.
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • putOpt

        public JSONObject putOpt​(java.lang.String name,
                                 java.lang.Object value)
                          throws JSONException
        Equivalent to put(name, value) when both parameters are non-null; does nothing otherwise.
        Parameters:
        name - the name of the property
        value - the value of the property
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • accumulate

        public JSONObject accumulate​(java.lang.String name,
                                     java.lang.Object value)
                              throws JSONException
        Appends value to the array already mapped to name. If this object has no mapping for name, this inserts a new mapping. If the mapping exists but its value is not an array, the existing and new values are inserted in order into a new array which is itself mapped to name. In aggregate, this allows values to be added to a mapping one at a time.
        Parameters:
        name - the name of the property
        value - a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL or null. May not be NaNs or infinities.
        Returns:
        this object.
        Throws:
        JSONException - if an error occurs
      • remove

        public java.lang.Object remove​(java.lang.String name)
        Removes the named mapping if it exists; does nothing otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value previously mapped by name, or null if there was no such mapping.
      • isNull

        public boolean isNull​(java.lang.String name)
        Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
        Parameters:
        name - the name of the property
        Returns:
        true if this object has no mapping for name
      • has

        public boolean has​(java.lang.String name)
        Returns true if this object has a mapping for name. The mapping may be NULL.
        Parameters:
        name - the name of the property
        Returns:
        true if this object has a mapping for name
      • get

        public java.lang.Object get​(java.lang.String name)
                             throws JSONException
        Returns the value mapped by name.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if no such mapping exists.
      • opt

        public java.lang.Object opt​(java.lang.String name)
        Returns the value mapped by name, or null if no such mapping exists.
        Parameters:
        name - the name of the property
        Returns:
        the value or null
      • getBoolean

        public boolean getBoolean​(java.lang.String name)
                           throws JSONException
        Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or cannot be coerced to a boolean.
      • optBoolean

        public boolean optBoolean​(java.lang.String name)
        Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean. Returns false otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value or null
      • optBoolean

        public boolean optBoolean​(java.lang.String name,
                                  boolean fallback)
        Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean. Returns fallback otherwise.
        Parameters:
        name - the name of the property
        fallback - a fallback value
        Returns:
        the value or fallback
      • getDouble

        public double getDouble​(java.lang.String name)
                         throws JSONException
        Returns the value mapped by name if it exists and is a double or can be coerced to a double.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or cannot be coerced to a double.
      • optDouble

        public double optDouble​(java.lang.String name)
        Returns the value mapped by name if it exists and is a double or can be coerced to a double. Returns NaN otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value or NaN
      • optDouble

        public double optDouble​(java.lang.String name,
                                double fallback)
        Returns the value mapped by name if it exists and is a double or can be coerced to a double. Returns fallback otherwise.
        Parameters:
        name - the name of the property
        fallback - a fallback value
        Returns:
        the value or fallback
      • getInt

        public int getInt​(java.lang.String name)
                   throws JSONException
        Returns the value mapped by name if it exists and is an int or can be coerced to an int.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or cannot be coerced to an int.
      • optInt

        public int optInt​(java.lang.String name)
        Returns the value mapped by name if it exists and is an int or can be coerced to an int. Returns 0 otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value of 0
      • optInt

        public int optInt​(java.lang.String name,
                          int fallback)
        Returns the value mapped by name if it exists and is an int or can be coerced to an int. Returns fallback otherwise.
        Parameters:
        name - the name of the property
        fallback - a fallback value
        Returns:
        the value or fallback
      • getLong

        public long getLong​(java.lang.String name)
                     throws JSONException
        Returns the value mapped by name if it exists and is a long or can be coerced to a long. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers over JSON.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or cannot be coerced to a long.
      • optLong

        public long optLong​(java.lang.String name)
        Returns the value mapped by name if it exists and is a long or can be coerced to a long. Returns 0 otherwise. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers via JSON.
        Parameters:
        name - the name of the property
        Returns:
        the value or 0L
      • optLong

        public long optLong​(java.lang.String name,
                            long fallback)
        Returns the value mapped by name if it exists and is a long or can be coerced to a long. Returns fallback otherwise. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers over JSON.
        Parameters:
        name - the name of the property
        fallback - a fallback value
        Returns:
        the value or fallback
      • getString

        public java.lang.String getString​(java.lang.String name)
                                   throws JSONException
        Returns the value mapped by name if it exists, coercing it if necessary.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if no such mapping exists.
      • optString

        public java.lang.String optString​(java.lang.String name)
        Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.
        Parameters:
        name - the name of the property
        Returns:
        the value or an empty string
      • optString

        public java.lang.String optString​(java.lang.String name,
                                          java.lang.String fallback)
        Returns the value mapped by name if it exists, coercing it if necessary. Returns fallback if no such mapping exists.
        Parameters:
        name - the name of the property
        fallback - a fallback value
        Returns:
        the value or fallback
      • getJSONArray

        public JSONArray getJSONArray​(java.lang.String name)
                               throws JSONException
        Returns the value mapped by name if it exists and is a JSONArray.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or is not a JSONArray.
      • optJSONArray

        public JSONArray optJSONArray​(java.lang.String name)
        Returns the value mapped by name if it exists and is a JSONArray. Returns null otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value or null
      • getJSONObject

        public JSONObject getJSONObject​(java.lang.String name)
                                 throws JSONException
        Returns the value mapped by name if it exists and is a JSONObject.
        Parameters:
        name - the name of the property
        Returns:
        the value
        Throws:
        JSONException - if the mapping doesn't exist or is not a JSONObject.
      • optJSONObject

        public JSONObject optJSONObject​(java.lang.String name)
        Returns the value mapped by name if it exists and is a JSONObject. Returns null otherwise.
        Parameters:
        name - the name of the property
        Returns:
        the value or null
      • toJSONArray

        public JSONArray toJSONArray​(JSONArray names)
        Returns an array with the values corresponding to names. The array contains null for names that aren't mapped. This method returns null if names is either null or empty.
        Parameters:
        names - the names of the properties
        Returns:
        the array
      • keys

        public java.util.Iterator keys()
        Returns an iterator of the String names in this object. The returned iterator supports remove, which will remove the corresponding mapping from this object. If this object is modified after the iterator is returned, the iterator's behavior is undefined. The order of the keys is undefined.
        Returns:
        the keys
      • names

        public JSONArray names()
        Returns an array containing the string names in this object. This method returns null if this object contains no mappings.
        Returns:
        the array
      • toString

        public java.lang.String toString()
        Encodes this object as a compact JSON string, such as:
        {"query":"Pizza","locations":[94043,90210]}
        Overrides:
        toString in class java.lang.Object
        Returns:
        a string representation of the object.
      • toString

        public java.lang.String toString​(int indentSpaces)
        Encodes this object as a human-readable JSON string for debugging, such as:
        
         {
             "query": "Pizza",
             "locations": [
                 94043,
                 90210
             ]
         }
         
        Parameters:
        indentSpaces - the number of spaces to indent for each level of nesting.
        Returns:
        a string representation of the object.
        Throws:
        java.lang.RuntimeException - if an error occurs
      • equals

        public boolean equals​(java.lang.Object o)
        Overrides:
        equals in class java.lang.Object
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class java.lang.Object
      • numberToString

        public static java.lang.String numberToString​(java.lang.Number number)
                                               throws JSONException
        Encodes the number as a JSON string.
        Parameters:
        number - a finite value. May not be NaNs or infinities.
        Returns:
        the encoded value
        Throws:
        JSONException - if an error occurs
      • quote

        public static java.lang.String quote​(java.lang.String data)
        Encodes data as a JSON string. This applies quotes and any necessary character escaping.
        Parameters:
        data - the string to encode. Null will be interpreted as an empty string.
        Returns:
        the quoted value
      • wrap

        public static java.lang.Object wrap​(java.lang.Object o)
        Wraps the given object if necessary.

        If the object is null or , returns NULL. If the object is a JSONArray or JSONObject, no wrapping is necessary. If the object is NULL, no wrapping is necessary. If the object is an array or Collection, returns an equivalent JSONArray. If the object is a Map, returns an equivalent JSONObject. If the object is a primitive wrapper type or String, returns the object. Otherwise if the object is from a java package, returns the result of toString. If wrapping fails, returns null.

        Parameters:
        o - the object to wrap
        Returns:
        the wrapped object