Package Torello.JSON
Class ParsePrimJSON
- java.lang.Object
-
- Torello.JSON.ParsePrimJSON
-
public class ParsePrimJSON extends java.lang.Object
Builds on the J2EE Standard Release JSON Parsing Tools by providing additional help with converting JSON Data into Java Primitive-Types
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 Glass Fish Tool is included in the J2EE, and is available on GitHub. That is the one used by the Java HTML JAR Library (See:javax.json.*)
Primary Classes Used:JsonArrayandJsonObject
This comment-note is intentionally repeated, verbatim, at the top of all Json Reader Classes in this package.
JSON to Java Binding:
JSON-Binding is the art of converting data that has been stored, saved or transmitted usingJava-Script Object Notationinto a Java Primitive or Object-Type.JSONcan arrive into Java-Program Memory from almost any source. If you are wondering why such a massive amount of "work" is necessary just to convert a Json Integer into Java Integer, the value added is the extraordinary amount of attention paid to user configuration, error checking, & exception messaging. Methods here don't require more than 1 or 2 lines of code, and guarantee that a thorough type checking is performed.
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 may or may not be assured. The methods here are able to handle changes that might be made to an API (possibly from great distances away, and without the Software-Manager's consent). If an error could occur, configuration flags can be used to determine default error-recovery behaviors. If an exception does throw, the exception messages printed will contain multiple lines of detailed information.- 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. Json Files can occasionally grow extremely large, and error messaging details make debugging easier
- Primary Helper-Classes for the (Experimental) Google-Chrome
Browser AutomationPackage
The goal ofTorello.JSONis to provide small, static helper methods in the same spirit asjava.util.Objectsandjava.util.Arrays: simple calls that keep JSON handling out of your application logic. Instead of repeating loops, type checks, null checks, and exception wiring at every call site, these methods centralize that work behind a consistent set of straight-forward “read value” operations.
Reads a single JSON STRING value from a JsonArray or JsonObject and parse it into a Java primitive. with strict type checking.
This class provides a precise and intentionally strict bridge between loosely-typed JSON data and Java’s fixed-width primitive types. JSON values may be missing, malformed, incorrectly typed, explicitly null, or numerically out of range; Java primitives permit none of these. Every method in this class performs full validation before returning a value.
If the requested JSON element does not exist, is not of the expected JSON type, represents a JsonNull, or cannot be converted exactly into the requested primitive without loss of information, an exception is thrown with detailed diagnostic context. Fail-fast behavior is intentional: data errors should be detected immediately, not silently propagated.
The API is deliberately symmetrical and minimal. Each primitive type is supported through two direct-access patterns:- Indexed lookup from a
JsonArray - Named lookup from a
JsonObject
This class performs no coercion, inference, or structural traversal. It is a low-level, deterministic parsing utility intended for use inside higher-level JSON processing logic where correctness, predictability, and exact numeric fidelity are required.
Optional User Parser
All public entry points accept anoptionalUserParserparameter. When this argument is non-null, the supplied lambda is invoked on the JSON string value and the standard Java parser is bypassed. This allows callers to support application-specific number formats while still keeping the rest of the validation in this class strict and diagnostic. To ignore this feature, simply passnulland the built-inInteger.parseInt/Long.parseLong/Double.parseDouble/ etc. logic is used.
For example, a payload may represent currency or decorated numbers as strings such as"$499.99","(-21)", or"#21". A caller can supply a tiny parser that strips the decoration and delegates to Java's normal parsing rules:
Example:
// JSON: { "price": "$499.99" } double price = ParsePrimJSON.getDouble( jo, "price", (String s) -> Double.parseDouble(s.substring(1)) ); // JSON: { "delta": "(-21)" } int delta = ParsePrimJSON.getInt( jo, "delta", (String s) -> -Integer.parseInt(s.substring(1, s.length() - 1)) 2);
Note that Chat-GPT wrote this cute little summary-thing. This is a "high level overview" of a class, and the more coding I do in life, the more impossible it becomes to generate English Word explanations for anything.
Method Parameters
Parameter Explanation jaA JsonArraywhose element (atindex) is expected to contain aJsonStringvalue to be parsed into a Java primitive.
These methods are specifically for parsing strings (example: a JSON string like"123") into a Java numeric primitive (or boolean primitive).indexThe zero-based array index of the element being parsed from ja.joA JsonObjectwhose property value (namedpropertyName) is expected to contain aJsonStringto be parsed into a Java primitive.propertyNameThe name of the JsonObjectproperty to retrieve fromjoand parse.optionalUserParserA user-supplied parsing function.
If non-null, this function is used to convert theJsonStringcontent into the target Java boxed value (example: parse an integer from a string).
This is intended for cases where the default parsing logic is insufficient (special formats, custom numeric rules, locale-sensitive parsing, etc.), or where you simply want to override parsing behavior.
Single Character:
Note that this class simply doesn't support any methods for reading achar. This is because their are just entirely too many possibilities, combinations & options for the appropriate "Default Behavior" when attempting to read a single character of data from any random JSON Data-Type.
Remember that the JSON Specification does not posses any "Single-JSON-Character" Data-Type. Creating some kind of Flag-Controlled Reader for a'char'that can capably decide what to do would be so overtly verbose, for something so simple, that it isn't worth the effort...- See Also:
JsonObject,JsonArray
Hi-Lited Source-Code:- View Here: Torello/JSON/ParsePrimJSON.java
- Open New Browser-Tab: Torello/JSON/ParsePrimJSON.java
File Size: 19,903 Bytes Line Count: 517 '\n' Characters Found
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctionalAnnotation may also be called 'The Spaghetti Report'.Static-Functionalclasses are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@StatelessAnnotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 16 Method(s), 16 declared static
- 0 Field(s)
- Utilizes the Java-Standard
-
-
Method Summary
From JsonArray: Retrieve a JsonStringfrom aJsonArrayand parse it into a Java PrimitiveModifier and Type Method static booleanparseBoolean(JsonArray ja, int index, Predicate<String> optionalUserParser)static byteparseByte(JsonArray ja, int index, ToByteFunction<String> optionalUserParser)static doubleparseDouble(JsonArray ja, int index, ToDoubleFunction<String> optionalUserParser)static floatparseFloat(JsonArray ja, int index, ToFloatFunction<String> optionalUserParser)static intparseInt(JsonArray ja, int index, ToIntFunction<String> optionalUserParser)static longparseLong(JsonArray ja, int index, ToLongFunction<String> optionalUserParser)static shortparseShort(JsonArray ja, int index, ToShortFunction<String> optionalUserParser)From JsonObject: Retrieve a JsonStringfrom aJsonObjectand parse it into a Java PrimitiveModifier and Type Method static booleanparseBoolean(JsonObject jo, String propertyName, Predicate<String> optionalUserParser)static byteparseByte(JsonObject jo, String propertyName, ToByteFunction<String> optionalUserParser)static doubleparseDouble(JsonObject jo, String propertyName, ToDoubleFunction<String> optionalUserParser)static floatparseFloat(JsonObject jo, String propertyName, ToFloatFunction<String> optionalUserParser)static intparseInt(JsonObject jo, String propertyName, ToIntFunction<String> optionalUserParser)static longparseLong(JsonObject jo, String propertyName, ToLongFunction<String> optionalUserParser)static shortparseShort(JsonObject jo, String propertyName, ToShortFunction<String> optionalUserParser)Internal Use Only: (Protected Methods) GET Modifier and Type Method protected static <T> JsonStringGET(JsonArray ja, int index, Class<T> primitiveClass)protected static <T> JsonStringGET(JsonObject jo, String propertyName, Class<T> primitiveClass)
-
-
-
Method Detail
-
parseInt
public static int parseInt (JsonArray ja, int index, java.util.function.ToIntFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'int' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java intprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, int.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsInt(js.getString()) : Integer.parseInt(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, int.class); }
-
parseLong
public static long parseLong (JsonArray ja, int index, java.util.function.ToLongFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'long' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java longprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, long.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsLong(js.getString()) : Long.parseLong(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, long.class); }
-
parseShort
public static short parseShort (JsonArray ja, int index, ToShortFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'short' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java shortprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, short.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsShort(js.getString()) : Short.parseShort(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, short.class); }
-
parseByte
public static byte parseByte (JsonArray ja, int index, ToByteFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'byte' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java byteprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, byte.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsByte(js.getString()) : Byte.parseByte(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, byte.class); }
-
parseDouble
public static double parseDouble (JsonArray ja, int index, java.util.function.ToDoubleFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'double' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java doubleprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, double.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsDouble(js.getString()) : Double.parseDouble(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, double.class); }
-
parseFloat
public static float parseFloat (JsonArray ja, int index, ToFloatFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'float' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java floatprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, float.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsFloat(js.getString()) : Float.parseFloat(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, float.class); }
-
parseBoolean
public static boolean parseBoolean (JsonArray ja, int index, java.util.function.Predicate<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonArray, and Parse into a Java 'boolean' PrimitiveAccepts: a JsonArray, along with an array index.Flags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java booleanprimitiveSee: Method GET(JsonArray, int, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(ja, index, boolean.class); try { return (optionalUserParser != null) ? optionalUserParser.test(js.getString()) : Boolean.parseBoolean(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseArrException(e, ja, index, js, boolean.class); }
-
GET
protected static <T> JsonString GET(JsonArray ja, int index, java.lang.Class<T> primitiveClass)
This is an internal helper method for retrieving an element from aJsonArray, and converting it to one of the standard Java Types.- Parameters:
ja- Any instance ofJsonArrayindex- Any index into the array which holds aJsonStringprimitiveClass- Expected Primitive Class, to be returned by caller method- Returns:
- The extracted
JsonString. - Throws:
JsonNullPrimitiveArrException- If the array element at'index'contains Json-NullJsonTypeArrException- If the array element at'index'doesn't containJsonStringjava.lang.IndexOutOfBoundsException- If'index'is out of the bounds of'ja'- See Also:
parseInt(JsonArray, int, ToIntFunction),parseLong(JsonArray, int, ToLongFunction),parseShort(JsonArray, int, ToShortFunction),parseByte(JsonArray, int, ToByteFunction),parseDouble(JsonArray, int, ToDoubleFunction),parseFloat(JsonArray, int, ToFloatFunction)- Code:
- Exact Method Body:
// This will throw an IndexOutOfBoundsException if the index is out of bounds. final JsonValue jv = ja.get(index); switch (jv.getValueType()) { // This particular Array-Location (the one specified by 'index') contained an actual // 'null' in its place. Primitives cannot be assinged null, but fortunately there is // a JsonException descendant class that handles this exact situation. case NULL: throw new JsonNullPrimitiveArrException (ja, index, STRING, primitiveClass); case STRING: return (JsonString) jv; // The JsonValue at the specified array-index does not contain a JsonString. default: throw new JsonTypeArrException (ja, index, STRING, jv, primitiveClass); }
-
parseInt
public static int parseInt (JsonObject jo, java.lang.String propertyName, java.util.function.ToIntFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'int' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java intprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, int.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsInt(js.getString()) : Integer.parseInt(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, int.class); }
-
parseLong
public static long parseLong (JsonObject jo, java.lang.String propertyName, java.util.function.ToLongFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'long' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java longprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, long.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsLong(js.getString()) : Long.parseLong(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, long.class); }
-
parseShort
public static short parseShort (JsonObject jo, java.lang.String propertyName, ToShortFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'short' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java shortprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, short.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsShort(js.getString()) : Short.parseShort(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, short.class); }
-
parseByte
public static byte parseByte (JsonObject jo, java.lang.String propertyName, ToByteFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'byte' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java byteprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, byte.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsByte(js.getString()) : Byte.parseByte(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, byte.class); }
-
parseDouble
public static double parseDouble (JsonObject jo, java.lang.String propertyName, java.util.function.ToDoubleFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'double' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java doubleprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, double.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsDouble(js.getString()) : Double.parseDouble(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, double.class); }
-
parseFloat
public static float parseFloat (JsonObject jo, java.lang.String propertyName, ToFloatFunction<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'float' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java floatprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, float.class); try { return (optionalUserParser != null) ? optionalUserParser.applyAsFloat(js.getString()) : Float.parseFloat(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, float.class); }
-
parseBoolean
public static boolean parseBoolean (JsonObject jo, java.lang.String propertyName, java.util.function.Predicate<java.lang.String> optionalUserParser)
Extract a JsonString from a JsonObject, and Parse into a Java 'boolean' PrimitiveAccepts: a JsonObject, along with property name, as ajava.lang.StringFlags: Does not accept user configuration flags. Instead, throws all default exceptions on error. Returns: A Java booleanprimitiveSee: Method GET(JsonObject, String, Class)User-Parser: Parmeter 'optionalUserParser'may be passed 'null'.When null, the parameter is ignored; Standard Java parse logic is used. - Code:
- Exact Method Body:
final JsonString js = GET(jo, propertyName, boolean.class); try { return (optionalUserParser != null) ? optionalUserParser.test(js.getString()) : Boolean.parseBoolean(js.getString().trim()); } catch (Exception e) { throw new JsonStrParseObjException(e, jo, propertyName, js, boolean.class); }
-
GET
protected static <T> JsonString GET(JsonObject jo, java.lang.String propertyName, java.lang.Class<T> primitiveClass)
This is an internal helper method for retrieving a property from aJsonObject, and converting it to one of the standard Java Types.- Parameters:
jo- Any instance ofJsonObjectpropertyName- Any property name contained by'jo', having aJsonStringprimitiveClass- Expected Primitive Class, to be returned by caller method- Returns:
- The extracted
JsonString. - Throws:
JsonNullPrimitiveObjException- If the specified property contains Json-NullJsonTypeObjException- If the specified property doesn't containJsonStringJsonPropMissingException- If the property is missing.- See Also:
parseInt(JsonObject, String, ToIntFunction),parseLong(JsonObject, String, ToLongFunction),parseShort(JsonObject, String, ToShortFunction),parseByte(JsonObject, String, ToByteFunction),parseDouble(JsonObject, String, ToDoubleFunction),parseFloat(JsonObject, String, ToFloatFunction)- Code:
- Exact Method Body:
// Here, a 'get' request was made for a property that isn't actually listed among the // properties in the provided JsonObject. Since this internal 'GET' is used by methods // that are trying to return a Java Primitive (like 'int' or 'float'), then an exception // has to be thrown. The option of returning 'null' isn't possible here! if (! jo.containsKey(propertyName)) throw new JsonPropMissingException (jo, propertyName, STRING, primitiveClass); final JsonValue jv = jo.get(propertyName); switch (jv.getValueType()) { // A Json-"null" was listed as the "value" assigned to this property // Primitive's cannot encode "null." Fortunately, there is a specialized Java-HTML // JsonException sub-class that handles exactly this type of situation. // // "someJsonObjectPropert": null, case NULL: throw new JsonNullPrimitiveObjException (jo, propertyName, STRING, primitiveClass); case STRING: return (JsonString) jv; // The JsonObject property does not contain a JsonString. default: throw new JsonTypeObjException (jo, propertyName, STRING, jv, primitiveClass); }
-
-