Class Parser

All Implemented Interfaces:
AnnotationProvider
Direct Known Subclasses:
InputStreamParser, Parser.Null, ParserSet.Inherit, ParserSet.NoInherit, ReaderParser

public class Parser extends BeanContextable
Parent class for all Juneau parsers.
Valid data conversions

Parsers can parse any parsable POJO types, as specified in the POJO Categories.

Some examples of conversions are shown below...

Data type Class type JSON example XML example Class examples
object Maps, Java beans {name:'John Smith',age:21} <object> <name type='string'>John Smith</name> <age type='number'>21</age> </object> HashMap, TreeMap<String,Integer>
array Collections, Java arrays [1,2,3] <array> <number>1</number> <number>2</number> <number>3</number> </array> List<Integer>, int[], Float[], Set<Person>
number Numbers 123 <number>123</number> Integer, Long, Float, int
boolean Booleans true <boolean>true</boolean> Boolean
string CharSequences 'foobar' <string>foobar</string> String, StringBuilder

In addition, any class types with ObjectSwaps associated with them on the registered bean context can also be passed in.

For example, if the TemporalCalendarSwap transform is used to generalize Calendar objects to String objects. When registered with this parser, you can construct Calendar objects from Strings using the following syntax...

Calendar calendar = parser.parse("'Sun Mar 03 04:05:06 EST 2001'", GregorianCalendar.class);

If Object.class is specified as the target type, then the parser automatically determines the data types and generates the following object types...

JSON typeClass type
objectJsonMap
arrayJsonList
numberNumber
(depending on length and format, could be Integer, Double, Float, etc...)
booleanBoolean
stringString
Notes:
  • This class is thread safe and reusable.
See Also:
  • Constructor Details

    • Parser

      protected Parser(Parser.Builder builder)
      Constructor.
      Parameters:
      builder - The builder this object.
  • Method Details

    • create

      public static Parser.Builder create()
      Creates a new builder for this object.
      Returns:
      A new builder.
    • createParserBuilder

      public static Parser.Builder createParserBuilder(Class<? extends Parser> c)
      Instantiates a builder of the specified parser class.

      Looks for a public static method called create that returns an object that can be passed into a public or protected constructor of the class.

      Parameters:
      c - The builder to create.
      Returns:
      A new builder.
    • copy

      public Parser.Builder copy()
      Description copied from class: Context
      Creates a builder from this context object.

      Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.

      Overrides:
      copy in class Context
      Returns:
      A new Builder object.
    • isReaderParser

      public boolean isReaderParser()
      Returns true if this parser subclasses from ReaderParser.
      Returns:
      true if this parser subclasses from ReaderParser.
    • parse

      public final <T> T parse(Object input, Type type, Type... args) throws ParseException, IOException
      Parses input into the specified object type.

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

      Examples:

      ReaderParser parser = JsonParser.DEFAULT; // Parse into a linked-list of strings. List list1 = parser.parse(json, LinkedList.class, String.class); // Parse into a linked-list of beans. List list2 = parser.parse(json, LinkedList.class, MyBean.class); // Parse into a linked-list of linked-lists of strings. List list3 = parser.parse(json, LinkedList.class, LinkedList.class, String.class); // Parse into a map of string keys/values. Map map1 = parser.parse(json, TreeMap.class, String.class, String.class); // Parse into a map containing string keys and values of lists containing beans. Map map2 = parser.parse(json, 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.

      Notes:
      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      input - The input.
      Character-based parsers can handle the following input class types:
      Stream-based parsers can handle the following input class types:
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by underlying stream.
      See Also:
    • parse

      public final <T> T parse(String input, Type type, Type... args) throws ParseException
      Same as parse(Object, Type, Type...) but since it's a String input doesn't throw an IOException.
      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
    • parse

      public final <T> T parse(Object input, Class<T> type) throws ParseException, IOException
      Same as parse(Object, Type, Type...) except optimized for a non-parameterized class.

      This is the preferred parse method for simple types since you don't need to cast the results.

      Examples:

      ReaderParser parser = JsonParser.DEFAULT; // Parse into a string. String string = parser.parse(json, String.class); // Parse into a bean. MyBean bean = parser.parse(json, MyBean.class); // Parse into a bean array. MyBean[] beanArray = parser.parse(json, MyBean[].class); // Parse into a linked-list of objects. List list = parser.parse(json, LinkedList.class); // Parse into a map of object keys/values. Map map = parser.parse(json, TreeMap.class);

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by the underlying stream.
    • parse

      public final <T> T parse(String input, Class<T> type) throws ParseException
      Same as parse(Object, Class) but since it's a String input doesn't throw an IOException.
      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
    • parse

      public final <T> T parse(Object input, ClassMeta<T> type) throws ParseException, IOException
      Same as parse(Object, Type, Type...) except the type has already been converted into a ClassMeta object.

      This is mostly an internal method used by the framework.

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by the underlying stream.
    • parse

      public final <T> T parse(String input, ClassMeta<T> type) throws ParseException
      Same as parse(Object, ClassMeta) but since it's a String input doesn't throw an IOException.
      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
    • createSession

      Description copied from class: Context
      Create a session builder based on the properties defined on this context.

      Use this method for creating sessions where you want to override basic settings. Otherwise, use Context.getSession() directly.

      Overrides:
      createSession in class Context
      Returns:
      A new session builder.
    • getSession

      Description copied from class: Context
      Returns a session to use for this context.

      Note that subclasses may opt to return a reusable non-modifiable session.

      Overrides:
      getSession in class Context
      Returns:
      A new session object.
    • doParse

      public <T> T doParse(ParserSession session, ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException
      Workhorse method.

      Subclasses are expected to either implement this method or ParserSession.doParse(ParserPipe, ClassMeta).

      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      session - The current session.
      pipe - Where to get the input from.
      type - The class type of the object to create. If null or Object.class, object type is based on what's being parsed. For example, when parsing JSON text, it may return a String, Number, JsonMap, etc...
      Returns:
      The parsed object.
      Throws:
      IOException - Thrown by underlying stream.
      ParseException - Malformed input encountered.
      ExecutableException - Exception occurred on invoked constructor/method/field.
    • parseIntoMap

      public final <K, V> Map<K,V> parseIntoMap(Object input, Map<K,V> m, Type keyType, Type valueType) throws ParseException
      Parses the contents of the specified reader and loads the results into the specified map.

      Reader must contain something that serializes to a map (such as text containing a JSON object).

      Used in the following locations:

      Type Parameters:
      K - The key class type.
      V - The value class type.
      Parameters:
      input - The input. See parse(Object, ClassMeta) for supported input types.
      m - The map being loaded.
      keyType - The class type of the keys, or null to default to String.class.
      valueType - The class type of the values, or null to default to whatever is being parsed.
      Returns:
      The same map that was passed in to allow this method to be chained.
      Throws:
      ParseException - Malformed input encountered.
      UnsupportedOperationException - If not implemented.
    • parseIntoCollection

      public final <E> Collection<E> parseIntoCollection(Object input, Collection<E> c, Type elementType) throws ParseException
      Parses the contents of the specified reader and loads the results into the specified collection.

      Used in the following locations:

      Type Parameters:
      E - The element class type.
      Parameters:
      input - The input. See parse(Object, ClassMeta) for supported input types.
      c - The collection being loaded.
      elementType - The class type of the elements, or null to default to whatever is being parsed.
      Returns:
      The same collection that was passed in to allow this method to be chained.
      Throws:
      ParseException - Malformed input encountered.
      UnsupportedOperationException - If not implemented.
    • parseArgs

      public final Object[] parseArgs(Object input, Type[] argTypes) throws ParseException
      Parses the specified array input with each entry in the object defined by the argTypes argument.

      Used for converting arrays (e.g. "[arg1,arg2,...]") into an Object[] that can be passed to the Method.invoke(target, args) method.

      Used in the following locations:

      Parameters:
      input - The input. Subclasses can support different input types.
      argTypes - Specifies the type of objects to create for each entry in the array.
      Returns:
      An array of parsed objects.
      Throws:
      ParseException - Malformed input encountered.
    • getMediaTypes

      public final List<MediaType> getMediaTypes()
      Returns the media types handled based on the values passed to the consumes constructor parameter.
      Returns:
      The list of media types. Never null.
    • getPrimaryMediaType

      Returns the first media type handled based on the values passed to the consumes constructor parameter.
      Returns:
      The media type.
    • canHandle

      public boolean canHandle(String contentType)
      Returns true if this parser can handle the specified content type.
      Parameters:
      contentType - The content type to test.
      Returns:
      true if this parser can handle the specified content type.
    • isAutoCloseStreams

      protected final boolean isAutoCloseStreams()
      Auto-close streams.
      Returns:
      true if InputStreams and Readers passed into parsers will be closed after parsing is complete.
      See Also:
    • getDebugOutputLines

      protected final int getDebugOutputLines()
      Debug output lines.
      Returns:
      The number of lines of input before and after the error location to be printed as part of the exception message.
      See Also:
    • getListener

      protected final Class<? extends ParserListener> getListener()
      Parser listener.
      Returns:
      Class used to listen for errors and warnings that occur during parsing.
      See Also:
    • isStrict

      protected final boolean isStrict()
      Strict mode.
      Returns:
      true if strict mode for the parser is enabled.
      See Also:
    • isTrimStrings

      protected final boolean isTrimStrings()
      Trim parsed strings.
      Returns:
      true if string values will be trimmed of whitespace using String.trim() before being added to the POJO.
      See Also:
    • isUnbuffered

      protected final boolean isUnbuffered()
      Unbuffered.
      Returns:
      true if parsers don't use internal buffering during parsing.
      See Also:
    • properties

      protected JsonMap properties()
      Description copied from class: Context
      Returns the properties on this bean as a map for debugging.
      Overrides:
      properties in class BeanContextable
      Returns:
      The properties on this bean as a map for debugging.