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

com.json.JSONArray Maven / Gradle / Ivy

The 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.util.*;

/**
 * A JSONArray is an ordered sequence of values. Its external text form is a
 * string wrapped in square brackets with commas separating the values. The
 * internal form is an object having get and opt
 * methods for accessing the values by index, and put methods for
 * adding or replacing values. The values can be any of these types:
 * Boolean, JSONArray, JSONObject,
 * Number, String, or the
 * JSONObject.NULL object.
 * 

* The constructor can convert a JSON text into a Java object. The * toString method converts to JSON text. *

* 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. *

* 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. *

* The texts produced by the toString methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: *

    *
  • An extra , (comma) may appear just * before the closing bracket.
  • *
  • The null value will be inserted when there is , *  (comma) elision.
  • *
  • Strings may be quoted with ' (single * quote).
  • *
  • Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, and * if they do not contain any of these characters: * { } [ ] / \ : , = ; # and if they do not look like numbers and * if they are not the reserved words true, false, or * null.
  • *
  • Values can be separated by ; (semicolon) as * well as by , (comma).
  • *
  • Numbers may have the 0- (octal) or * 0x- (hex) prefix.
  • *
  • Comments written in the slashshlash, slashstar, and hash conventions will * be ignored.
  • *
* * @author JSON.org * @version 3 */ public class JSONArray implements List, Serializable { private static final long serialVersionUID = 1L; /** * The arrayList where the JSONArray's properties are kept. */ private List myList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myList = new ArrayList(); } /** * Construct a JSONArray from a JSONTokener. * * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() == ']') { return; } x.back(); for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myList.add(null); } else { x.back(); this.myList.add(x.nextValue()); } switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } /** * Construct a JSONArray from a source sJSON text. * * @param string A string that begins with [ (left * bracket) and ends with ] *  (right bracket). * @throws JSONException If there is a syntax error. */ public JSONArray(String string) throws JSONException { this(new JSONTokener(string)); } /** * Construct a JSONArray from a Collection. * * @param collection A Collection. */ public JSONArray(Collection collection) { this.myList = (collection == null) ? new ArrayList() : new ArrayList( collection); } /** * 获取当前对象中所有内容 * * @return List */ public List getContext() { return this.myList; } /** * 清理内容 */ public void clear() { if (this.myList != null) { this.myList.clear(); } } /** * 删除某个对象 * * @param index index */ public Object remove(int index) { if (this.myList != null) { return this.myList.remove(index); } return null; } /** * Get the object value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return An object value. */ public Object get(int index) { Object o = opt(index); if (isNull(index)) { return null; } return o; } /** * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean getBoolean(int index) { return RTUtil.toboolean(get(index)); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public double getdouble(int index) { return RTUtil.todouble(get(index)); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @param defaultValue defaultValue * @return The value. */ public double getdouble(int index, double defaultValue) { return RTUtil.todouble(get(index), defaultValue); } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public int getInt(int index) { return RTUtil.toInt(get(index)); } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @param defaultValue defaultValue * @return The value. */ public int getInt(int index, int defaultValue) { return RTUtil.toInt(get(index), defaultValue); } /** * Get int index * * @param index index * @return int */ public Integer getInteger(int index) { return RTUtil.toInteger(get(index)); } /** * Get int index * * @param index index * @param defaultValue defaultValue * @return int */ public Integer getInteger(int index, int defaultValue) { return RTUtil.toInteger(get(index), defaultValue); } /** * Get the JSONArray associated with an index. * * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. value is not a JSONArray */ public JSONArray getJSONArray(int index) { Object o = get(index); if (o != null && o instanceof JSONArray) { return (JSONArray) o; } return null; } /** * Get the JSONObject associated with an index. * * @param index subscript * @return A JSONObject value. */ public JSONObject getJSONObject(int index) { Object o = get(index); if (o instanceof JSONObject) { return (JSONObject) o; } return null; } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public long getlong(int index) { return RTUtil.tolong(get(index)); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @param defaultValue defaultValue * @return The value. */ public long getlong(int index, long defaultValue) { return RTUtil.tolong(get(index), defaultValue); } /** * Get Long value * * @param index index * @return Long */ public Long getLong(int index) { return RTUtil.toLong(get(index)); } /** * Get Long value * * @param index index * @param defaultValue defaultValue * @return long */ public Long getLong(int index, long defaultValue) { return RTUtil.toLong(get(index), defaultValue); } /** * Get the string associated with an index. * * @param index The index must be between 0 and length() - 1. * @return A string value. */ public String getString(int index) { return RTUtil.val(get(index)); } /** * Get the string associated with an index. * * @param index The index must be between 0 and length() - 1. * @param defaultValue defaultValue * @return A string value. */ public String getString(int index, String defaultValue) { return RTUtil.val(get(index), defaultValue); } /** * Determine if the value is null. * * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(opt(index)); } /** * Make a string from the contents of this JSONArray. * The separator string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myList.size(); } /** * Get the optional object value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return An object value, or null if there is no object at that index. */ private Object opt(int index) { return (index < 0 || index >= length()) ? null : this.myList.get(index); } /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myList.add(value); return this; } /** * Put or replace an object value in the JSONArray. * If the index is greater than the length of the JSONArray, then null elements will be added as necessary to pad it out. * * @param index The subscript. * @param value The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or * String, or the JSONObject.NULL object. * @return JSONArray */ public JSONArray put(int index, Object value) { this.myList.set(index, value); return this; } /** * insert object * * @param index index * @param value value */ public void insert(int index, Object value) { if (this.myList == null) { this.myList = new ArrayList(); return; } if (this.myList.size() == 0) { this.myList.add(value); return; } if (index >= myList.size()) { myList.add(value); return; } int i = 1; for (ListIterator iterator = this.myList.listIterator(); iterator .hasNext(); ) { if (index == 0) { iterator.add(value); return; } iterator.next(); if (i == index) { iterator.add(value); return; } else { i = i + 1; } } } public JSONArray copy() { try { return new JSONArray(this.toString()); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Make a JSON text of this JSONArray. For compactness, no unnecessary * whitespace is added. If it is not possible to produce a syntactically * correct JSON text then null will be returned instead. This could occur if * the array contains an invalid number. *

* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the * array. */ public String toString() { try { return '[' + join(",") + ']'; } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. 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, transmittable representation of the * object, beginning with [ (left * bracket) and ending with ] *  (right bracket). */ public String toString(int indentFactor) { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONArray. 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 indention of the top level. * @return a printable, displayable, transmittable representation of the * array. */ String toString(int indentFactor, int indent) { int len = length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray 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; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myList.get(i); if (v instanceof JSONObject) { ((JSONObject) v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray) v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } public boolean add(Object e) { return myList.add(e); } public void add(int index, Object element) { myList.add(index, element); } public boolean addAll(Collection c) { return myList.addAll(c); } public boolean addAll(int index, Collection c) { return myList.addAll(index, c); } public boolean contains(Object o) { return myList.contains(o); } public boolean containsAll(Collection c) { return myList.containsAll(c); } public int indexOf(Object o) { return myList.indexOf(o); } public boolean isEmpty() { return myList.isEmpty(); } public Iterator iterator() { return myList.iterator(); } public int lastIndexOf(Object o) { return myList.lastIndexOf(o); } public ListIterator listIterator() { return myList.listIterator(); } public ListIterator listIterator(int index) { return myList.listIterator(index); } public boolean remove(Object o) { return myList.remove(o); } public boolean removeAll(Collection c) { return myList.removeAll(c); } public boolean retainAll(Collection c) { return myList.retainAll(c); } public Object set(int index, Object element) { return myList.set(index, element); } public int size() { return myList.size(); } public List subList(int fromIndex, int toIndex) { return myList.subList(fromIndex, toIndex); } public Object[] toArray() { return myList.toArray(); } public Object[] toArray(Object[] a) { return myList.toArray(a); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy