org.apache.juneau.json.JsonParser Maven / Gradle / Ivy
// ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
// * with the License. You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an *
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the *
// * specific language governing permissions and limitations under the License. *
// ***************************************************************************************************************************
package org.apache.juneau.json;
import org.apache.juneau.*;
import org.apache.juneau.parser.*;
/**
* Parses any valid JSON text into a POJO model.
*
* Media types
*
* Handles Content-Type
types: application/json, text/json
*
* Description
*
* This parser uses a state machine, which makes it very fast and efficient. It parses JSON in about 70% of the
* time that it takes the built-in Java DOM parsers to parse equivalent XML.
*
*
* This parser handles all valid JSON syntax.
* In addition, when strict mode is disable, the parser also handles the following:
*
* -
* Javascript comments (both {@code /*} and {@code //}) are ignored.
*
-
* Both single and double quoted strings.
*
-
* Automatically joins concatenated strings (e.g.
"aaa" + 'bbb'
).
* -
* Unquoted attributes.
*
*
*
* Also handles negative, decimal, hexadecimal, octal, and double numbers, including exponential notation.
*
*
* This parser handles the following input, and automatically returns the corresponding Java class.
*
* -
* JSON objects (
"{...}" ) are converted to {@link ObjectMap ObjectMaps}.
* Note: If a _type ='xxx'
attribute is specified on the object, then an
* attempt is made to convert the object to an instance of the specified Java bean class.
* See the beanTypeName
setting on the {@link PropertyStore} for more information about parsing
* beans from JSON.
* -
* JSON arrays (
"[...]" ) are converted to {@link ObjectList ObjectLists}.
* -
* JSON string literals (
"'xyz'" ) are converted to {@link String Strings}.
* -
* JSON numbers (
"123" , including octal/hexadecimal/exponential notation) are converted to
* {@link Integer Integers}, {@link Long Longs}, {@link Float Floats}, or {@link Double Doubles} depending on
* whether the number is decimal, and the size of the number.
* -
* JSON booleans (
"false" ) are converted to {@link Boolean Booleans}.
* -
* JSON nulls (
"null" ) are converted to null .
* -
* Input consisting of only whitespace or JSON comments are converted to
null .
*
*
*
* Input can be any of the following:
*
* -
*
"{...}" - Converted to a {@link ObjectMap} or an instance of a Java bean if a _type
* attribute is present.
* -
*
"[...]" - Converted to a {@link ObjectList}.
* -
*
"123..." - Converted to a {@link Number} (either {@link Integer}, {@link Long}, {@link Float},
* or {@link Double}).
* -
*
"true" /"false" - Converted to a {@link Boolean}.
* -
*
"null" - Returns null .
* -
*
"'xxx'" - Converted to a {@link String}.
* -
*
"\"xxx\"" - Converted to a {@link String}.
* -
*
"'xxx' + \"yyy\"" - Converted to a concatenated {@link String}.
*
*
*
* TIP: If you know you're parsing a JSON object or array, it can be easier to parse it using the
* {@link ObjectMap#ObjectMap(CharSequence) ObjectMap(CharSequence)} or {@link ObjectList#ObjectList(CharSequence)
* ObjectList(CharSequence)} constructors instead of using this class.
* The end result should be the same.
*/
public class JsonParser extends ReaderParser {
//-------------------------------------------------------------------------------------------------------------------
// Configurable properties
//-------------------------------------------------------------------------------------------------------------------
private static final String PREFIX = "JsonParser.";
/**
* Configuration property: Validate end.
*
*
Property:
*
* - Name:
"JsonParser.validateEnd.b"
* - Data type:
Boolean
* - Default:
false
* - Session property:
false
* - Methods:
*
* - {@link JsonParserBuilder#validateEnd(boolean)}
*
- {@link JsonParserBuilder#validateEnd()}
*
*
*
* Description:
*
* If true , after parsing a POJO from the input, verifies that the remaining input in
* the stream consists of only comments or whitespace.
*
*
Example:
*
* // Create a parser that validates that there's no garbage at the end of the input.
* ReaderParser p = JsonParser.
* .create ()
* .validateEnd()
* .build();
*
* // Same, but use property.
* ReaderParser p = JsonParser.
* .create ()
* .set(JSON_validateEnd , true )
* .build();
*
* // Should fail because input has multiple POJOs.
* String in = "{foo:'bar'}{baz:'qux'}" ;
* MyBean myBean = p.parse(in, MyBean.class );
*
*/
public static final String JSON_validateEnd = PREFIX + "validateEnd.b";
//-------------------------------------------------------------------------------------------------------------------
// Predefined instances
//-------------------------------------------------------------------------------------------------------------------
/** Default parser, all default settings.*/
public static final JsonParser DEFAULT = new JsonParser.Simple(PropertyStore.DEFAULT);
/** Default parser, all default settings.*/
public static final JsonParser DEFAULT_STRICT = new JsonParser.Strict(PropertyStore.DEFAULT);
//-------------------------------------------------------------------------------------------------------------------
// Predefined subclasses
//-------------------------------------------------------------------------------------------------------------------
/** Default parser, strict mode. */
public static class Strict extends JsonParser {
/**
* Constructor.
*
* @param ps The property store containing all the settings for this object.
*/
public Strict(PropertyStore ps) {
super(ps.builder().set(PARSER_strict, true).set(JSON_validateEnd, true).build());
}
}
/** Default parser, simple mode. */
public static class Simple extends JsonParser {
/**
* Constructor.
*
* @param ps The property store containing all the settings for this object.
*/
public Simple(PropertyStore ps) {
super(ps, "application/json+simple", "text/json+simple");
}
}
//-------------------------------------------------------------------------------------------------------------------
// Instance
//-------------------------------------------------------------------------------------------------------------------
private final boolean validateEnd;
/**
* Constructor.
*
* @param ps The property store containing all the settings for this object.
*/
public JsonParser(PropertyStore ps) {
this(ps, "application/json", "text/json");
}
/**
* Constructor.
*
* @param ps The property store containing all the settings for this object.
* @param consumes The list of media types that this parser consumes (e.g. "application/json" ).
*/
public JsonParser(PropertyStore ps, String...consumes) {
super(ps, consumes);
validateEnd = getBooleanProperty(JSON_validateEnd, false);
}
@Override /* Context */
public JsonParserBuilder builder() {
return new JsonParserBuilder(getPropertyStore());
}
/**
* Instantiates a new clean-slate {@link JsonParserBuilder} object.
*
*
* This is equivalent to simply calling new JsonParserBuilder()
.
*
*
* Note that this method creates a builder initialized to all default settings, whereas {@link #builder()} copies
* the settings of the object called on.
*
* @return A new {@link JsonParserBuilder} object.
*/
public static JsonParserBuilder create() {
return new JsonParserBuilder();
}
@Override /* Parser */
public ReaderParserSession createSession(ParserSessionArgs args) {
return new JsonParserSession(this, args);
}
//-----------------------------------------------------------------------------------------------------------------
// Properties
//-----------------------------------------------------------------------------------------------------------------
/**
* Configuration property: Validate end.
*
* @see #JSON_validateEnd
* @return
* true if after parsing a POJO from the input, verifies that the remaining input in
* the stream consists of only comments or whitespace.
*/
protected final boolean isValidateEnd() {
return validateEnd;
}
@Override /* Context */
public ObjectMap asMap() {
return super.asMap()
.append("JsonParser", new ObjectMap());
}
}