Class JsonList

All Implemented Interfaces:
Serializable, Cloneable, Iterable<Object>, Collection<Object>, Deque<Object>, List<Object>, Queue<Object>
Direct Known Subclasses:
DelegateList

public class JsonList extends LinkedList<Object>
Java implementation of a JSON array.

An extension of LinkedList, so all methods available to in that class are also available to this class.

Note that the use of this class is optional for generating JSON. The serializers will accept any objects that implement the Collection interface. But this class provides some useful additional functionality when working with JSON models constructed from Java Collections Framework objects. For example, a constructor is provided for converting a JSON array string directly into a List. It also contains accessor methods for to avoid common typecasting when accessing elements in a list.

Example:

// Construct an empty List JsonList list = JsonList.of(); // Construct a list of objects using various methods list = JsonList.of().a("foo").a(123).a(true); list = JsonList.of().a("foo", 123, true); // Equivalent list = JsonList.of("foo", 123, true); // Equivalent // Construct a list of integers from JSON list = JsonList.ofJson("[1,2,3]"); // Construct a list of generic JsonMap objects from JSON list = JsonList.ofJson("[{foo:'bar'},{baz:'bing'}]"); // Construct a list of integers from XML String xml = "<array><number>1</number><number>2</number><number>3</number></array>"; list = JsonList.of(xml, XmlParser.DEFAULT); list = (List)XmlParser.DEFAULT.parse(xml); // Equivalent list = (List)XmlParser.DEFAULT.parse(Object.class, xml); // Equivalent list = XmlParser.DEFAULT.parse(List.class, xml); // Equivalent list = XmlParser.DEFAULT.parse(JsonList.class, xml); // Equivalent // Construct JSON from JsonList list = JsonList.ofJson("[{foo:'bar'},{baz:'bing'}]"); String json = list.toString(); // Produces "[{foo:'bar'},{baz:'bing'}]" json = list.toString(JsonSerializer.DEFAULT); // Equivalent json = JsonSerializer.DEFAULT.serialize(list); // Equivalent // Get one of the entries in the list as an Integer list = JsonList.ofJson("[1,2,3]"); Integer integer = list.getInt(1); list = list.get(Integer.class, 1); // Equivalent // Get one of the entries in the list as an Float list = JsonList.ofJson("[1,2,3]"); Float _float = list.getFloat(1); // Returns 2f _float = list.get(Float.class, 1); // Equivalent // Same as above, except converted to a String list = JsonList.ofJson("[1,2,3]"); String string = list.getString(1); // Returns "2" string = list.get(String.class, 1); // Equivalent // Get one of the entries in the list as a bean (converted to a bean if it isn't already one) list = JsonList.ofJson("[{name:'John Smith',age:45}]"); Person person = list.get(Person.class, 0); // Iterate over a list of beans using the elements() method list = JsonList.ofJson("[{name:'John Smith',age:45}]"); for (Person person : list.elements(Person.class) { // Do something with p }

Notes:
  • This class is not thread safe.
See Also:
  • Field Details

  • Constructor Details

    • JsonList

      public JsonList()
      Construct an empty list.
    • JsonList

      public JsonList(BeanSession session)
      Construct an empty list with the specified bean context.
      Parameters:
      session - The bean session to use for creating beans.
    • JsonList

      public JsonList(Collection<?> copyFrom)
      Construct a list initialized with the specified list.
      Parameters:
      copyFrom - The list to copy.
      Can be null.
    • JsonList

      public JsonList(CharSequence json) throws ParseException
      Construct a list initialized with the specified JSON.
      Parameters:
      json - The JSON text to parse.
      Can be normal or simplified JSON.
      Throws:
      ParseException - Malformed input encountered.
    • JsonList

      public JsonList(CharSequence in, Parser p) throws ParseException
      Construct a list initialized with the specified string.
      Parameters:
      in - The input being parsed.
      Can be null.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Throws:
      ParseException - Malformed input encountered.
    • JsonList

      public JsonList(Reader json) throws ParseException
      Construct a list initialized with the specified reader containing JSON.
      Parameters:
      json - The reader containing JSON text to parse.
      Can contain normal or simplified JSON.
      Throws:
      ParseException - Malformed input encountered.
    • JsonList

      public JsonList(Reader in, Parser p) throws ParseException
      Construct a list initialized with the specified string.
      Parameters:
      in - The reader containing the input being parsed.
      Can contain normal or simplified JSON.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Throws:
      ParseException - Malformed input encountered.
    • JsonList

      public JsonList(Object... entries)
      Construct a list initialized with the contents.
      Parameters:
      entries - The entries to add to this list.
  • Method Details

    • ofJsonOrCdl

      public static JsonList ofJsonOrCdl(String s) throws ParseException
      Parses a string that can consist of either a JSON array or comma-delimited list.

      The type of string is auto-detected.

      Parameters:
      s - The string to parse.
      Returns:
      The parsed string.
      Throws:
      ParseException - Malformed input encountered.
    • create

      public static JsonList create()
      Construct an empty list.
      Returns:
      An empty list.
    • of

      public static JsonList of(Collection<?> values)
      Construct a list initialized with the specified list.
      Parameters:
      values - The list to copy.
      Can be null.
      Returns:
      A new list or null if the list was null.
    • ofCollections

      public static JsonList ofCollections(Collection<?>... values)
      Convenience method for creating a list of collection objects.
      Parameters:
      values - The initial values.
      Returns:
      A new list.
    • ofArrays

      public static JsonList ofArrays(Object[]... values)
      Convenience method for creating a list of array objects.
      Parameters:
      values - The initial values.
      Returns:
      A new list.
    • ofJson

      public static JsonList ofJson(CharSequence json) throws ParseException
      Construct a list initialized with the specified JSON string.
      Parameters:
      json - The JSON text to parse.
      Can be normal or simplified JSON.
      Returns:
      A new list or null if the string was null.
      Throws:
      ParseException - Malformed input encountered.
    • ofText

      public static JsonList ofText(CharSequence in, Parser p) throws ParseException
      Construct a list initialized with the specified string.
      Parameters:
      in - The input being parsed.
      Can be null.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Returns:
      A new list or null if the input was null.
      Throws:
      ParseException - Malformed input encountered.
    • ofJson

      public static JsonList ofJson(Reader json) throws ParseException
      Construct a list initialized with the specified reader containing JSON.
      Parameters:
      json - The reader containing JSON text to parse.
      Can contain normal or simplified JSON.
      Returns:
      A new list or null if the input was null.
      Throws:
      ParseException - Malformed input encountered.
    • ofText

      public static JsonList ofText(Reader in, Parser p) throws ParseException
      Construct a list initialized with the specified string.
      Parameters:
      in - The reader containing the input being parsed.
      Can contain normal or simplified JSON.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Returns:
      A new list or null if the input was null.
      Throws:
      ParseException - Malformed input encountered.
    • of

      public static JsonList of(Object... values)
      Construct a list initialized with the specified values.
      Parameters:
      values - The values to add to this list.
      Returns:
      A new list, never null.
    • session

      public JsonList session(BeanSession session)
      Override the default bean session used for converting POJOs.

      Default is BeanContext.DEFAULT, which is sufficient in most cases.

      Useful if you're serializing/parsing beans with transforms defined.

      Parameters:
      session - The new bean session.
      Returns:
      This object.
    • append

      public JsonList append(Object value)
      Adds the value to this list.
      Parameters:
      value - The value to add to this list.
      Returns:
      This object.
    • append

      public JsonList append(Object... values)
      Adds all the values in the specified array to this list.
      Parameters:
      values - The values to add to this list.
      Returns:
      This object.
    • append

      public JsonList append(Collection<?> values)
      Adds all the values in the specified collection to this list.
      Parameters:
      values - The values to add to this list.
      Returns:
      This object.
    • appendIf

      public JsonList appendIf(boolean flag, Object value)
      Adds an entry to this list if the boolean flag is true.
      Parameters:
      flag - The boolean flag.
      value - The value to add.
      Returns:
      This object.
    • appendReverse

      public JsonList appendReverse(List<?> values)
      Adds all the entries in the specified collection to this list in reverse order.
      Parameters:
      values - The collection to add to this list.
      Returns:
      This object.
    • appendReverse

      public JsonList appendReverse(Object... values)
      Adds the contents of the array to the list in reverse order.

      i.e. add values from the array from end-to-start order to the end of the list.

      Parameters:
      values - The collection to add to this list.
      Returns:
      This object.
    • appendIf

      public <T> JsonList appendIf(Predicate<T> test, T value)
      Add if predicate matches.
      Type Parameters:
      T - The type being tested.
      Parameters:
      test - The predicate to match against.
      value - The value to add if the predicate matches.
      Returns:
      This object.
    • get

      public <T> T get(int index, Class<T> type)
      Get the entry at the specified index, converted to the specified type.

      This is the preferred get method for simple types.

      Examples:

      JsonList list = JsonList.ofJson("..."); // Value converted to a string. String string = list.get(1, String.class); // Value converted to a bean. MyBean bean = list.get(2, MyBean.class); // Value converted to a bean array. MyBean[] beanArray = list.get(3, MyBean[].class); // Value converted to a linked-list of objects. List list2 = list.get(4, LinkedList.class); // Value converted to a map of object keys/values. Map map = list.get(5, TreeMap.class);

      See BeanSession.convertToType(Object, ClassMeta) for the list of valid data conversions.

      Type Parameters:
      T - The type of object to convert the entry to.
      Parameters:
      index - The index into this list.
      type - The type of object to convert the entry to.
      Returns:
      The converted entry.
    • get

      public <T> T get(int index, Type type, Type... args)
      Get the entry at the specified index, converted to the specified type.

      The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps).

      Examples:

      JsonList list = JsonList.ofJson("..."); // Value converted to a linked-list of strings. List<String> list1 = list.get(1, LinkedList.class, String.class); // Value converted to a linked-list of beans. List<MyBean> list2 = list.get(2, LinkedList.class, MyBean.class); // Value converted to a linked-list of linked-lists of strings. List<List<String>> list3 = list.get(3, LinkedList.class, LinkedList.class, String.class); // Value converted to a map of string keys/values. Map<String,String> map1 = list.get(4, TreeMap.class, String.class, String.class); // Value converted to a map containing string keys and values of lists containing beans. Map<String,List<MyBean>> map2 = list.get(5, TreeMap.class, String.class, List.class, MyBean.class);

      Collection classes are assumed to be followed by zero or one objects indicating the element type.

      Map classes are assumed to be followed by zero or two meta objects indicating the key and value types.

      The array can be arbitrarily long to indicate arbitrarily complex data structures.

      See BeanSession.convertToType(Object, ClassMeta) for the list of valid data conversions.

      Type Parameters:
      T - The type of object to convert the entry to.
      Parameters:
      index - The index into this list.
      type - The type of object to convert the entry to.
      args - The type arguments of the type to convert the entry to.
      Returns:
      The converted entry.
    • getString

      public String getString(int index)
      Shortcut for calling get(index, String.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
    • getInt

      public Integer getInt(int index)
      Shortcut for calling get(index, Integer.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getBoolean

      public Boolean getBoolean(int index)
      Shortcut for calling get(index, Boolean.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getLong

      public Long getLong(int index)
      Shortcut for calling get(index, Long.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getMap

      public JsonMap getMap(int index)
      Shortcut for calling get(index, JsonMap.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getMap

      public <K, V> Map<K,V> getMap(int index, Class<K> keyType, Class<V> valType)
      Same as getMap(int) except converts the keys and values to the specified types.
      Type Parameters:
      K - The key type class.
      V - The value type class.
      Parameters:
      index - The index.
      keyType - The key type class.
      valType - The value type class.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getList

      public JsonList getList(int index)
      Shortcut for calling get(index, JsonList.class).
      Parameters:
      index - The index.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getList

      public <E> List<E> getList(int index, Class<E> elementType)
      Same as getList(int) except converts the elements to the specified types.
      Type Parameters:
      E - The element type.
      Parameters:
      index - The index.
      elementType - The element type class.
      Returns:
      The converted value.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getAt

      public <T> T getAt(String path, Class<T> type)
      Same as get(int,Class), but the key is a slash-delimited path used to traverse entries in this POJO.

      For example, the following code is equivalent:

      JsonList list = JsonList.ofJson("..."); // Long way long long1 = list.getMap("0").getLong("baz"); // Using this method long long2 = list.getAt("0/baz", long.class);

      This method uses the ObjectRest class to perform the lookup, so the map can contain any of the various class types that the ObjectRest class supports (e.g. beans, collections, arrays).

      Type Parameters:
      T - The class type.
      Parameters:
      path - The path to the entry.
      type - The class type.
      Returns:
      The value, or null if the entry doesn't exist.
    • getAt

      public <T> T getAt(String path, Type type, Type... args)
      Same as getAt(String,Class), but allows for conversion to complex maps and collections.
      Type Parameters:
      T - The class type.
      Parameters:
      path - The path to the entry.
      type - The class type.
      args - The class parameter types.
      Returns:
      The value, or null if the entry doesn't exist.
    • putAt

      public Object putAt(String path, Object o)
      Same as set(int,Object), but the key is a slash-delimited path used to traverse entries in this POJO.

      For example, the following code is equivalent:

      JsonList list = JsonList.ofJson("..."); // Long way list.getMap("0").put("baz", 123); // Using this method list.putAt("0/baz", 123);

      This method uses the ObjectRest class to perform the lookup, so the map can contain any of the various class types that the ObjectRest class supports (e.g. beans, collections, arrays).

      Parameters:
      path - The path to the entry.
      o - The new value.
      Returns:
      The previous value, or null if the entry doesn't exist.
    • postAt

      public Object postAt(String path, Object o)
      Similar to putAt(String,Object), but used to append to collections and arrays.

      For example, the following code is equivalent:

      JsonList list = JsonList.ofJson("..."); // Long way list.getMap(0).getList("bar").append(123); // Using this method list.postAt("0/bar", 123);

      This method uses the ObjectRest class to perform the lookup, so the map can contain any of the various class types that the ObjectRest class supports (e.g. beans, collections, arrays).

      Parameters:
      path - The path to the entry.
      o - The new value.
      Returns:
      The previous value, or null if the entry doesn't exist.
    • deleteAt

      public Object deleteAt(String path)
      Similar to remove(int),but the key is a slash-delimited path used to traverse entries in this POJO.

      For example, the following code is equivalent:

      JsonList list = JsonList.ofJson("..."); // Long way list.getMap(0).getList("bar").delete(0); // Using this method list.deleteAt("0/bar/0");

      This method uses the ObjectRest class to perform the lookup, so the map can contain any of the various class types that the ObjectRest class supports (e.g. beans, collections, arrays).

      Parameters:
      path - The path to the entry.
      Returns:
      The previous value, or null if the entry doesn't exist.
    • getBeanSession

      Returns the BeanSession currently associated with this list.
      Returns:
      The BeanSession currently associated with this list.
    • setBeanSession

      Sets the BeanSession currently associated with this list.
      Parameters:
      value - The BeanSession currently associated with this list.
      Returns:
      This object.
    • elements

      public <E> Iterable<E> elements(Class<E> childType)
      Creates an Iterable with elements of the specified child type.

      Attempts to convert the child objects to the correct type if they aren't already the correct type.

      The next() method on the returned iterator may throw a InvalidDataConversionException if the next element cannot be converted to the specified type.

      See BeanSession.convertToType(Object, ClassMeta) for a description of valid conversions.

      Example:

      // Iterate over a list of JsonMaps. JsonList list = JsonList.ofJson("[{foo:'bar'},{baz:123}]"); for (JsonMap map : list.elements(JsonMap.class)) { // Do something with map. } // Iterate over a list of ints. JsonList list = JsonList.ofJson("[1,2,3]"); for (Integer i : list.elements(Integer.class)) { // Do something with i. } // Iterate over a list of beans. // Automatically converts to beans. JsonList list = JsonList.ofJson("[{name:'John Smith',age:45}]"); for (Person p : list.elements(Person.class)) { // Do something with p. }

      Type Parameters:
      E - The child object type.
      Parameters:
      childType - The child object type.
      Returns:
      A new Iterable object over this list.
    • getClassMeta

      public ClassMeta<?> getClassMeta(int index)
      Returns the ClassMeta of the class of the object at the specified index.
      Parameters:
      index - An index into this list, zero-based.
      Returns:
      The data type of the object at the specified index, or null if the value is null.
    • asString

      public String asString(WriterSerializer serializer)
      Serialize this array to a string using the specified serializer.
      Parameters:
      serializer - The serializer to use to convert this object to a string.
      Returns:
      This object as a serialized string.
    • asString

      public String asString()
      Serialize this array to Simplified JSON.
      Returns:
      This object as a serialized string.
    • isUnmodifiable

      public boolean isUnmodifiable()
      Returns true if this list is unmodifiable.
      Returns:
      true if this list is unmodifiable.
    • modifiable

      public JsonList modifiable()
      Returns a modifiable copy of this list if it's unmodifiable.
      Returns:
      A modifiable copy of this list if it's unmodifiable, or this list if it is already modifiable.
    • unmodifiable

      Returns an unmodifiable copy of this list if it's modifiable.
      Returns:
      An unmodifiable copy of this list if it's modifiable, or this list if it is already unmodifiable.
    • writeTo

      Convenience method for serializing this JsonList to the specified Writer using the JsonSerializer.DEFAULT serializer.
      Parameters:
      w - The writer to send the serialized contents of this object.
      Returns:
      This object.
      Throws:
      IOException - If a problem occurred trying to write to the writer.
      SerializeException - If a problem occurred trying to convert the output.
    • cast

      public Object cast(ClassMeta<?> cm)
      Converts this object into the specified class type.

      TODO - The current implementation is very inefficient.

      Parameters:
      cm - The class type to convert this object to.
      Returns:
      A converted object.
    • asJson

      public String asJson()
      A synonym for toString()
      Returns:
      This object as a JSON string.
    • toString

      public String toString()
      Overrides:
      toString in class AbstractCollection<Object>