Class ReadArrJSON


  • public class ReadArrJSON
    extends java.lang.Object
    JSON Binding Helper-Class:
    JSON-Binding is the art of converting data that has been stored, saved or transmitted using Java-Script Object Notation into a Primitive-Type or Object-Type of any Programming Language, for instance Java. JSON often arrives into Java-Program Memory from an external Internet Connection, and may have traveled hundreds or even thousands of miles from a Host-Server.

    Unlike Java-Types which are checked by the Java-Compiler each-and-every time a programmer compiles his project, any guarantee that JSON-Type Data is pristine, uncorrupted, and in any kind of pre-agreed format is never completely assured.

    Being able to handle changes that might be made to an API (possibly from great distances away, and without the Software-Manager's consent) is the type of feature that robust JSON-Code simply has to offer.

    Binding-Helper Features:
    • Utilizes the Java-Standard javax.json.* Package-Library, & its Glass-Fish Implementation
    • Handles the Transfer & Conversion of All Json-Type's into Java-Type's with just One Line of Code
    • Provides all manner of User-Configurable Exception-Handling & Error-Decision Management via Class JFlag
    • Provides a Fine-Grained Suite of Exception-Classes, all with Consistent & Meaningful Error-Messages
    • Primary Helper-Classes for the (Experimental) Google-Chrome Headless Browser Package
    Utilities for parsing Json Array's into Java Array's.

    This class builds on the J2EE Standard 'Glass-Fish' JSON Processor

    There are several JSON Parsers available, and even more implementations for serializing and de-serializing data to/from JSON. The tool included in the J2EE is available on GitHub, and that is the one used by the Java HTML JAR Library. (See: javax.json.* )

    Primary Classes Used: JsonArray and JsonObject

    The methods in this class simplify converting a JsonArray into one of the following types:

    • Simple Primitive-Array, such as: int[], double[] or boolean[]
    • Primitive-Stream (Java provides precisely three: IntStream, LongStream and DoubleStream)
    • Stream of Boxed-Primitives: Stream<Integer>, Stream<Boolean> etc...


    Below are some examples of JsonArray's. These arrays are perfectly legal in JSON, but present some problems to Java Programmers. A simple one line invocation follows in the example after this, for parsing these JSON-Arrays into Java-Arrays - without throwing exceptions:

    Java Script Object Notation (JSON):
    {
        "intArr" :          [1, 2, 3, 4, 5],
        "floatArr" :        [1.1, 2.2, 3.3, 4.4, 5.5],
    
        "intArrSurprise":   ["1", 2, "3", null, 5],
        "floatArrSurprise": ["1.1", 2.2, "3.3", true, 5.5]
    }
    


    In the example code, below, the above JSON is parsed into Java-Arrays:

    Example:
    String          json    = Scrape.scrapePage(new URL("http://some.url.com/some/REST/endpoint"));
    StringReader    sr      = new StringReader(json);
    JsonObject      jo      = Json.createReader(sr).readObject();
    
    // Simple Parse, without any problems
    int[] intArr = ReadArrJSON.intArrToStream
        (jo.getJsonArray("intArr"), -1, 0, null).toArray();
    
    // Simple Parse, without any problems
    float[] floatArr = ReadArrJSON.floatArray
        (jo.getJsonArray("floatArr"), -1, 0 null);
    
    
    // Flag RETURN_PARSE_ON_STR  ==>  Attempt to Parse String's into Integer's
    // Flag RETURN_DEFVAL_ON_NULL ==>  Insert a "4" if there are any nulls in the array
    
    int[] intSurprise = ReadArrJSON.intArrToStream(
            jo.getJsonArray("intArrSurprise"),
            4,
            RETURN_PARSE_ON_STR | RETURN_DEFVAL_ON_NULL,
            null
        )
        .toArray();
    
    // Flag RETURN_PARSE_ON_STR  ==>  Attempt to Parse String's into Float's
    // Flag RETURN_DEFVAL_ON_WRONG_JSONTYPE  ==>  Insert a "4.4" if there are any problematic types
        
    float[] floatSurprise = ReadArrJSON.floatArray(
        jo.getJsonArray("floatArrSurprise"),
        4.4,
        RETURN_PARSE_ON_STR | RETURN_DEFVAL_ON_WRONG_JSONTYPE,
        null
    );
    


    There are also methods provided in this class for generating a Stream<String> or a Stream<Object>.



    Boxed-Primitives & The Java Stream API
    Any java.util.stream.Stream may be easily converted into other types. The example below shows how to convert a Stream<T> into other types of containers, and it is hopefully obvious that 'T' should be substituted by any of the Boxed-Primitive Type's which are used in this class:
    Conversion-Target Stream-Method Invocation
    T[] Stream.toArray(T[]::new);
    List<T> Stream.collect(Collectors.toList());
    Vector<T> Stream.collect(Collectors.toCollection(Vector::new));
    TreeSet<T> Stream.collect(Collectors.toCollection(TreeSet::new));
    Iterator<T> Stream.iterator();


    Primitive Stream's
    Java has three Primitive-Stream types: IntStream, LongStream and DoubleStream. These are also easily converted into array's via the following:
    StreamArray
    IntStreamint[] arr = IntStream.toArray()
    LongStreamlong[] arr = LongStream.toArray()
    DoubleStreamdouble[] arr = DoubleStream.toArray()
    See Also:
    Json, Json, JsonArray



    Stateless Class:
    This class neither contains any program-state, nor can it be instantiated. The @StaticFunctional Annotation may also be called 'The Spaghetti Report'. Static-Functional classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's @Stateless Annotation.

    • 1 Constructor(s), 1 declared private, zero-argument constructor
    • 30 Method(s), 30 declared static
    • 7 Field(s), 7 declared static, 7 declared final


    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class
      static class  ReadArrJSON.DimN
    • Method Summary

       
      Stream<String>: Read a JsonArray into a Java Stream<String>
      Modifier and Type Method
      static Stream<String> strArrayToStream​(JsonArray ja, String defaultValue, int FLAGS)
       
      Stream<Object>: Read a JsonArray into a Java Stream<Object>
      Modifier and Type Method
      static <T> Stream<T> objArrayToStream​(JsonArray ja, T defaultValue, int FLAGS, Class<T> returnClass)
       
      Primitive-Stream: Read a JsonArray to a Primitive-Stream (easily converts to an array)
      Modifier and Type Method
      static DoubleStream doubleArrayToStream​(JsonArray ja, double defaultValue, int FLAGS, ToDoubleFunction<String> optionalUserParser)
      static IntStream intArrayToStream​(JsonArray ja, int defaultValue, int FLAGS, ToIntFunction<String> optionalUserParser)
      static LongStream longArrayToStream​(JsonArray ja, long defaultValue, int FLAGS, ToLongFunction<String> optionalUserParser)
       
      Boxed-Primitive Stream: Read a JsonArray into a Java Stream of Boxed-Types
      Modifier and Type Method
      static Stream<Boolean> booleanArrayToBoxedStream​(JsonArray ja, boolean defaultValue, int FLAGS, Function<String,​Boolean> optionalUserParser)
      static Stream<Byte> byteArrayToBoxedStream​(JsonArray ja, byte defaultValue, int FLAGS, Function<String,​Byte> optionalUserParser)
      static Stream<Double> doubleArrayToBoxedStream​(JsonArray ja, double defaultValue, int FLAGS, Function<String,​Double> optionalUserParser)
      static Stream<Float> floatArrayToBoxedStream​(JsonArray ja, float defaultValue, int FLAGS, Function<String,​Float> optionalUserParser)
      static Stream<Integer> integerArrayToBoxedStream​(JsonArray ja, int defaultValue, int FLAGS, Function<String,​Integer> optionalUserParser)
      static Stream<Long> longArrayToBoxedStream​(JsonArray ja, long defaultValue, int FLAGS, Function<String,​Long> optionalUserParser)
      static Stream<Number> numberArrayToBoxedStream​(JsonArray ja, Number defaultValue, int FLAGS, Function<String,​Number> optionalUserParser)
      static Stream<Short> shortArrayToBoxedStream​(JsonArray ja, short defaultValue, int FLAGS, Function<String,​Short> optionalUserParser)
       
      Primitive-Array: Read a JsonArray into a Simple Java (Un-Boxed) Primitive-Array
      Modifier and Type Method
      static boolean[] booleanArray​(JsonArray ja, boolean defaultValue, int FLAGS, Predicate<String> optionalUserParser)
      static byte[] byteArray​(JsonArray ja, byte defaultValue, int FLAGS, ToByteFunction<String> optionalUserParser)
      static float[] floatArray​(JsonArray ja, float defaultValue, int FLAGS, ToFloatFunction<String> optionalUserParser)
      static short[] shortArray​(JsonArray ja, short defaultValue, int FLAGS, ToShortFunction<String> optionalUserParser)
       
      Protected, Internal Methods
      Modifier and Type Method
      protected static <T,​U>
      U
      boxedStreamToPrimitiveArray​(Stream<T> boxedStream, JsonArray ja, Class<T> returnClass, ObjIntConsumer<T> arrayBuilder, U retArr)
      protected static <T,​U>
      U
      jsonArrToBoxedStream​(JsonArray ja, Torello.Java.JSON.ReadArrJSON.RECORD<T,​U> rec)
      protected static <T,​U>
      U
      jsonArrToStream​(JsonArray ja, Torello.Java.JSON.ReadArrJSON.RECORD<T,​U> rec)
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • intArrayToStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.IntStream intArrayToStream​
                    (JsonArray ja,
                     int defaultValue,
                     int FLAGS,
                     java.util.function.ToIntFunction<java.lang.String> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToStream(JsonArray, RECORD)
        Passes: Java IntStream Configurtion-Record
        Removes: Any JFlag masks which might insert null-entries in the return-stream
        For information about the JFlag parameter, click the method link above.

        Producing a standard java int[] array from an IntStream is a trivial-converstion:

        Java Line of Code:
         int[] arr = intArrayToStream(ja, -1, 0, null).toArray();
        
      • longArrayToStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.LongStream longArrayToStream​
                    (JsonArray ja,
                     long defaultValue,
                     int FLAGS,
                     java.util.function.ToLongFunction<java.lang.String> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToStream(JsonArray, RECORD)
        Passes: Java LongStream Configurtion-Record
        Removes: Any JFlag masks which might insert null-entries in the return-stream
        For information about the JFlag parameter, click the method link above.

        Producing a standard java long[] array from a LongStream is a trivial-converstion:

        Java Line of Code:
         long[] arr = longArrayToStream(ja, -1, 0, null).toArray();
        
      • doubleArrayToStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.DoubleStream doubleArrayToStream​
                    (JsonArray ja,
                     double defaultValue,
                     int FLAGS,
                     java.util.function.ToDoubleFunction<java.lang.String> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToStream(JsonArray, RECORD)
        Passes: Java DoubleStream Configurtion-Record
        Removes: Any JFlag masks which might insert null-entries in the return-stream
        For information about the JFlag parameter, click the method link above.

        Producing a standard java double[] array from a DoubleStream is a trivial-converstion:

        Java Line of Code:
         double[] arr = doubleArrayToStream(ja, -1, 0, null).toArray();
        
      • boxedStreamToPrimitiveArray

        🡅  🡇     🗕  🗗  🗖
        protected static <T,​U> U boxedStreamToPrimitiveArray​
                    (java.util.stream.Stream<T> boxedStream,
                     JsonArray ja,
                     java.lang.Class<T> returnClass,
                     java.util.function.ObjIntConsumer<T> arrayBuilder,
                     U retArr)
        
        Converts a Java Boxed Stream to a Primitive Array.
        Type Parameters:
        T - The generic-type of the java.util.stream.Stream
        U - The returned primitive-array type
        Parameters:
        boxedStream - A Java Boxed Stream
        arrayBuilder - A consumer which inserts a Boxed-Number into the Primitive-Array
        ja - The JsonArray that generated the Boxed-Stream. Needed for error-output
        returnClass - The java.lang.Class (generic-type parameter) for the Stream. In other words, the Class for type-parameter <T>. This is only needed if there is an exception, for proper & readable error-reporting.
        Code:
        Exact Method Body:
         // Since the array-index is used inside of a LAMBDA, this "EffectivelyFinal" counter
         // class becomes necessary.
        
         Counter counter = new Counter(-1);
        
         // Don't forget, Stream's are not guaranteed to be processed in order, unless an
         // explicit request is made using something like 'forEachOrdered'
        
         boxedStream.forEachOrdered((T boxedPrimitive) ->
         {
             int i = counter.addOne();   // "Final, or Effectively Final"
        
             // A Primitive-Array (like int[], long[], boolean[] etc...) may not have null
             if (boxedPrimitive == null)
                 throw new JsonNullPrimitiveArrException(ja, i, NUMBER, returnClass);
        
             // The 'arrayBuilder' just assigns the value to the array[i]
             arrayBuilder.accept(boxedPrimitive, i);
         });
            
         return retArr;
        
      • integerArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Integer> integerArrayToBoxedStream​
                    (JsonArray ja,
                     int defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Integer> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Integer-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Integer Array from this Method is as Follows:

        Java Line of Code:
         Integer[] arr = integerArrayToBoxedStream(ja, -1, 0 null).toArray(Integer[]::new);
        
      • shortArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Short> shortArrayToBoxedStream​
                    (JsonArray ja,
                     short defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Short> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Short-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Short Array from this Method is as Follows:

        Java Line of Code:
         Short[] arr = shortArrayToBoxedStream(ja, -1, 0 null).toArray(Short[]::new);
        
      • byteArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Byte> byteArrayToBoxedStream​
                    (JsonArray ja,
                     byte defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Byte> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Byte-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Byte Array from this Method is as Follows:

        Java Line of Code:
         Byte[] arr = byteArrayToBoxedStream(ja, -1, 0 null).toArray(Byte[]::new);
        
      • longArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Long> longArrayToBoxedStream​
                    (JsonArray ja,
                     long defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Long> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Long-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Long Array from this Method is as Follows:

        Java Line of Code:
         Long[] arr = longArrayToBoxedStream(ja, -1, 0 null).toArray(Long[]::new);
        
      • doubleArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Double> doubleArrayToBoxedStream​
                    (JsonArray ja,
                     double defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Double> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Double-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Double Array from this Method is as Follows:

        Java Line of Code:
         Double[] arr = doubleArrayToBoxedStream(ja, -1, 0 null).toArray(Double[]::new);
        
      • floatArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Float> floatArrayToBoxedStream​
                    (JsonArray ja,
                     float defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Float> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Float-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Float Array from this Method is as Follows:

        Java Line of Code:
         Float[] arr = floatArrayToBoxedStream(ja, -1, 0 null).toArray(Float[]::new);
        
      • numberArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Number> numberArrayToBoxedStream​
                    (JsonArray ja,
                     java.lang.Number defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Number> optionalUserParser)
        
        Convenience Method
        Invokes: jsonArrToBoxedStream(JsonArray, RECORD)
        Fills in Configuration Record for Number-Retrieval
        For more Information about the JFlag Parameter, Click the Method-Link above.

        Producing a Boxed-Number Array from this Method is as Follows:

        Java Line of Code:
         Number[] arr = numberArrayToBoxedStream(ja, -1, 0 null).toArray(Number[]::new);
        
      • strArrayToStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.String> strArrayToStream​
                    (JsonArray ja,
                     java.lang.String defaultValue,
                     int FLAGS)
        
        Converts a JsonArray into a Stream<String>. A Java Stream<String> is easily converted to a String[]-Array via a call to:

        Java Line of Code:
         String[] sArr = strArrayToStream(myJsonArray, null, 0).toArray(String[]::new);
        
        Parameters:
        ja - Any JsonArray, but preferrably one which contains instances of JsonString
        defaultValue - When used in conjunction with 'FLAGS', this default-value may be inserted into the output-array when error cases occur at particular array-index locations.
        FLAGS - Optional flags. See JFlag for details.
        Returns:
        A Java Stream<String>.
        Code:
        Exact Method Body:
         return strArrayToStreamINTERNAL(ja, RECORD.getStringStreamRec(defaultValue, FLAGS));
        
      • booleanArrayToBoxedStream

        🡅  🡇     🗕  🗗  🗖
        public static java.util.stream.Stream<java.lang.Boolean> booleanArrayToBoxedStream​
                    (JsonArray ja,
                     boolean defaultValue,
                     int FLAGS,
                     java.util.function.Function<java.lang.String,​java.lang.Boolean> optionalUserParser)
        
        Converts a JsonArray into a Stream<Boolean>. A Java Stream<Boolean> is easily converted to a Boolean[]-Array via a call to the lines below. Note that in this example, the return array is an array of Boolean objects; it is not a primitive boolean[] array. (To parse into a primitive array, use booleanArray(JsonArray, boolean, int, Predicate))

        Java Line of Code:
         Boolean[] bArr = booleanArrayToBoxedStream(myJsonArray, false, 0, null)
              .toArray(Boolean[]::new);
        
        Parameters:
        ja - Any JsonArray, but preferrably one which contains instances of JsonValue.TRUE or JsonValue.FALSE
        defaultValue - When used in conjunction with 'FLAGS', this default-value may be inserted into the output-array when error cases occur at particular array-index locations.
        FLAGS - Optional flags. See JFlag for details.
        optionalUserParser - If the appropriate flags are set, if a JsonString is encountered while processing the JsonArray, an attempt to parse the String into a Boolean will be made using this String-parser.
        Returns:
        A Java Stream<Boolean>.
        Code:
        Exact Method Body:
         return booleanArrayToBoxedStreamINTERNAL(
             ja,
             RECORD.getBOOLEANStreamRec
                 (defaultValue, FLAGS, optionalUserParser, false)
         );
        
      • objArrayToStream

        🡅     🗕  🗗  🗖
        public static <T> java.util.stream.Stream<T> objArrayToStream​
                    (JsonArray ja,
                     T defaultValue,
                     int FLAGS,
                     java.lang.Class<T> returnClass)
        
        Converts a JsonArray into a Stream<T>. It is important to remember that the package Torello.Java.JSON does not attempt to generate Java-Type's or their Constructors. The 'Type' of the Stream<T> that is returned by this method (the value of 'T') must be an Object-Class that contains a Constructor that accepts a JsonObject as input.

        This package does not perform the type of Auto-Type-Generation that is done by Lombok or Jackson.

        Note that a Java Stream<T> is easily converted to a T[]-Array via a call to the line below.

        Java Line of Code:
         MyClass[] bArr = objArrayToStream(myJsonArray, null, 0, MyClass.class)
              .toArray(MyClass[]::new);
        
        Type Parameters:
        T - This is the 'type' of the array being built. If there were a class, for example, named 'Automobile', the value passed to parameter 'returnClass' would simply be Automobile.class.
        Parameters:
        ja - Any JsonArray, but preferrably one which contains instances of the class that has been specified by Type-Parameter 'T'
        defaultValue - When used in conjunction with 'FLAGS', this default-value may be inserted into the output-array when error-cases occur while interpreting the array contents.
        FLAGS - Optional flags. See JFlag for details.
        returnClass - The java.lang.Class of the returned / output Stream-Type currently being constructed & filled.
        Returns:
        A Java Stream<T>.
        Code:
        Exact Method Body:
         return objArrayToStreamINTERNAL
             (ja, RECORD.getObjectStreamRec(defaultValue, FLAGS, returnClass));