📄 jsonobject.java
字号:
package org.json;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.text.ParseException;
/**
* 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.
* <p>
* The constructor can convert an external form string into an internal form
* Java object. The toString() method creates an external form string.
* <p>
* 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.
* <p>
* The generic get() and opt() methods return an object, which you can cast or
* query for type. There are also typed get() and opt() methods that do type
* checking and type coersion for you.
* <p>
* The texts produced by the toString() methods are very strict.
* The constructors are more forgiving in the texts they will accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just before the closing brace.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not contain leading
* or trailing spaces, and if they do not contain any of these characters:
* <code>{ } [ ] / \ : , ' "</code></li>
* <li>Numbers may have the 0- (octal) or 0x- (hex) prefix.</li>
* </ul>
* <p>
* Public Domain 2002 JSON.org
* @author JSON.org
* @version 0.1
*/
public class JSONObject {
/**
* 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 {
/**
* Make a Null object.
*/
private Null() {
}
/**
* There is only intended to be a single instance of the NULL object,
* so the clone method returns itself.
* @return NULL.
*/
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.
*/
public boolean equals(Object object) {
return object == null || object == this;
}
/**
* Get the "null" string value.
* @return The string "null".
*/
public String toString() {
return "null";
}
}
/**
* The hash map where the JSONObject's properties are kept.
*/
private HashMap myHashMap;
/**
* 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() {
myHashMap = new HashMap();
}
/**
* Construct a JSONObject from a JSONTokener.
* @param x A JSONTokener object containing the source string.
* @throws ParseException if there is a syntax error in the source string.
*/
public JSONObject(JSONTokener x) throws ParseException {
this();
char c;
String key;
if (x.next() == '%') {
x.unescape();
}
x.back();
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject must begin with '{'");
}
while (true) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
if (x.nextClean() != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
myHashMap.put(key, x.nextValue());
switch (x.nextClean()) {
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
/**
* Construct a JSONObject from a string.
*
* @param string A string beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @exception ParseException The string must be properly formatted.
*/
public JSONObject(String string) throws ParseException {
this(new JSONTokener(string));
}
/**
* 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) {
myHashMap = new HashMap(map);
}
/**
* 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 NullPointerException if the key is null
*/
public JSONObject accumulate(String key, Object value)
throws NullPointerException {
JSONArray a;
Object o = opt(key);
if (o == null) {
put(key, value);
} else if (o instanceof JSONArray) {
a = (JSONArray)o;
a.put(value);
} else {
a = new JSONArray();
a.put(o);
a.put(value);
put(key, a);
}
return this;
}
/**
* Get the value object associated with a key.
*
*
* @param key A key string.
* @return The object associated with the key.
* @exception NoSuchElementException if the key is not found.
*/
public Object get(String key) throws NoSuchElementException {
Object o = opt(key);
if (o == null) {
throw new NoSuchElementException("JSONObject[" +
quote(key) + "] not found.");
}
return o;
}
/**
* Get the boolean value associated with a key.
* @param key A key string.
* @return The truth.
*
* @exception NoSuchElementException if the key is not found.
* @exception ClassCastException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key)
throws ClassCastException, NoSuchElementException {
Object o = get(key);
if (o == Boolean.FALSE || o.equals("false")) {
return false;
} else if (o == Boolean.TRUE || o.equals("true")) {
return true;
}
throw new ClassCastException("JSONObject[" +
quote(key) + "] is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @exception NoSuchElementException if the key is not found or
* if the value is a Number object.
* @exception NumberFormatException if the value cannot be converted to a
* number.
*/
public double getDouble(String key)
throws NoSuchElementException, NumberFormatException {
Object o = get(key);
if (o instanceof Number) {
return ((Number)o).doubleValue();
}
if (o instanceof String) {
return new Double((String)o).doubleValue();
}
throw new NumberFormatException("JSONObject[" +
quote(key) + "] is not a number.");
}
/**
* Get the HashMap the holds that contents of the JSONObject.
* @return The getHashMap.
*/
HashMap getHashMap() {
return myHashMap;
}
/**
* Get the int value associated with a key.
* @param key A key string.
* @return The integer value.
* @exception NoSuchElementException if the key is not found
* @exception NumberFormatException if the value cannot be converted to a number.
*/
public int getInt(String key)
throws NoSuchElementException, NumberFormatException {
Object o = get(key);
if (o instanceof Number) {
return ((Number)o).intValue();
}
return (int)getDouble(key);
}
/**
* Get the JSONArray value associated with a key.
* @param key A key string.
* @return A JSONArray which is the value.
* @exception NoSuchElementException if the key is not found or
* if the value is not a JSONArray.
*/
public JSONArray getJSONArray(String key) throws NoSuchElementException {
Object o = get(key);
if (o instanceof JSONArray) {
return (JSONArray)o;
}
throw new NoSuchElementException("JSONObject[" +
quote(key) + "] is not a JSONArray.");
}
/**
* Get the JSONObject value associated with a key.
*
* @param key A key string.
* @return A JSONObject which is the value.
* @exception NoSuchElementException if the key is not found or
* if the value is not a JSONObject.
*/
public JSONObject getJSONObject(String key) throws NoSuchElementException {
Object o = get(key);
if (o instanceof JSONObject) {
return (JSONObject)o;
}
throw new NoSuchElementException("JSONObject[" +
quote(key) + "] is not a JSONObject.");
}
/**
* Get the string associated with a key.
* @param key A key string.
* @return A string which is the value.
* @exception NoSuchElementException if the key is not found.
*/
public String getString(String key) throws NoSuchElementException {
return get(key).toString();
}
/**
* 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 myHashMap.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 myHashMap.keySet().iterator();
}
/**
* Get the number of keys stored in the JSONObject.
*
* @return The number of keys in the JSONObject.
*/
public int length() {
return myHashMap.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());
}
if (ja.length() == 0) {
return null;
}
return ja;
}
/**
* Produce a string from a number.
* @param n A Number
* @return A String.
* @exception ArithmeticException JSON can only serialize finite numbers.
*/
static public String numberToString(Number n) throws ArithmeticException {
if (
(n instanceof Float &&
(((Float)n).isInfinite() || ((Float)n).isNaN())) ||
(n instanceof Double &&
(((Double)n).isInfinite() || ((Double)n).isNaN()))) {
throw new ArithmeticException(
"JSON can only serialize finite numbers.");
}
// Shave off trailing zeros and decimal point, if possible.
String s = n.toString().toLowerCase();
if (s.indexOf('e') < 0 && s.indexOf('.') > 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.
* @exception NullPointerException The key must not be null.
*/
public Object opt(String key) throws NullPointerException {
if (key == null) {
throw new NullPointerException("Null key");
}
return myHashMap.get(key);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -