All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.pwall.json.parser.Parser Maven / Gradle / Ivy

/*
 * @(#) Parser.java
 *
 * json-simple  Simple JSON Parser and Formatter
 * Copyright (c) 2021, 2022 Peter Wall
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package net.pwall.json.parser;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import net.pwall.json.JSONFunctions;
import net.pwall.text.TextMatcher;
import net.pwall.util.ImmutableList;
import net.pwall.util.ImmutableMap;
import net.pwall.util.ImmutableMapEntry;

/**
 * A simple JSON parser.  This class consists of static functions that parse JSON into standard Java classes, avoiding
 * the need for additional class definitions.
 *
 * @author  Peter Wall
 */
public class Parser {

    public static final String ROOT_POINTER = "";
    public static final int MAX_INTEGER_DIGITS_LENGTH = 10;

    public static final String EXCESS_CHARS = "Excess characters following JSON";
    public static final String ILLEGAL_NUMBER = "Illegal JSON number";
    public static final String ILLEGAL_SYNTAX = "Illegal JSON syntax";
    public static final String ILLEGAL_KEY = "Illegal key in JSON object";
    public static final String DUPLICATE_KEY = "Duplicate key in JSON object";
    public static final String MISSING_COLON = "Missing colon in JSON object";
    public static final String MISSING_CLOSING_BRACE = "Missing closing brace in JSON object";
    public static final String MISSING_CLOSING_BRACKET = "Missing closing bracket in JSON array";

    /**
     * Parse a string of JSON and return a value of type J (not an actual parameterised type), where
     * J is one of the following:
     *
     * 
*
{@link String}
*
for a JSON string
*
{@link Integer}
*
for a JSON integer, up to 32 bits
*
{@link Long}
*
for a JSON integer, 33 to 64 bits
*
{@link BigDecimal}
*
for all other JSON numbers, including floating point
*
{@link Boolean}
*
for the JSON keywords {@code true} and {@code false}
*
{@link List}<J>
*
for a JSON array
*
{@link Map}<{@link String}, J>
*
for a JSON object
*
{@code null}
*
for the JSON keyword {@code null}
*
* * @param json the JSON string * @return the object, as described above * @throws ParseException if there are any errors in the JSON */ public static Object parse(String json) { TextMatcher tm = new TextMatcher(json); Object result = parse(tm, ROOT_POINTER); tm.skip(JSONFunctions::isSpaceCharacter); if (!tm.isAtEnd()) throw new ParseException(EXCESS_CHARS); return result; } /** * Parse a JSON element from the current position of a {@link TextMatcher}. The index is left positioned after the * end of the element. * * @param tm a {@link TextMatcher} * @param pointer a string in JSON Pointer syntax * describing the position in the result JSON (for use in error reporting) * @return the JSON element * @throws ParseException if there are any errors in the JSON */ private static Object parse(TextMatcher tm, String pointer) { tm.skip(JSONFunctions::isSpaceCharacter); if (tm.match('{')) { ImmutableMapEntry[] array = ImmutableMap.createArray(8); int index = 0; tm.skip(JSONFunctions::isSpaceCharacter); if (!tm.match('}')) { while (true) { if (!tm.match('"')) throw new ParseException(ILLEGAL_KEY, pointer); String key = parseString(tm, pointer); if (ImmutableMap.containsKey(array, index, key)) throw new ParseException(DUPLICATE_KEY, pointer); tm.skip(JSONFunctions::isSpaceCharacter); if (!tm.match(':')) throw new ParseException(MISSING_COLON, pointer); if (index == array.length) { ImmutableMapEntry[] newArray = ImmutableMap.createArray(array.length + Math.min(array.length, 4096)); System.arraycopy(array, 0, newArray, 0, array.length); array = newArray; } array[index++] = ImmutableMap.entry(key, parse(tm, pointer + '/' + key)); tm.skip(JSONFunctions::isSpaceCharacter); if (!tm.match(',')) break; tm.skip(JSONFunctions::isSpaceCharacter); } if (!tm.match('}')) throw new ParseException(MISSING_CLOSING_BRACE, pointer); } return ImmutableMap.mapOf(array, index); } if (tm.match('[')) { Object[] array = new Object[16]; int index = 0; tm.skip(JSONFunctions::isSpaceCharacter); if (!tm.match(']')) { do { if (index == array.length) { Object[] newArray = new Object[array.length + Math.min(array.length, 4096)]; System.arraycopy(array, 0, newArray, 0, array.length); array = newArray; } array[index] = parse(tm, pointer + '/' + index); index++; tm.skip(JSONFunctions::isSpaceCharacter); } while (tm.match(',')); if (!tm.match(']')) throw new ParseException(MISSING_CLOSING_BRACKET, pointer); } return ImmutableList.listOf(array, index); } if (tm.match('"')) return parseString(tm, pointer); if (tm.match("true")) return Boolean.TRUE; if (tm.match("false")) return Boolean.FALSE; if (tm.match("null")) return null; int numberStart = tm.getIndex(); boolean negative = tm.match('-'); if (tm.matchDec(0, 1)) { int integerLength = tm.getResultLength(); if (integerLength > 1 && tm.getResultChar() == '0') throw new ParseException(ILLEGAL_NUMBER, pointer); boolean floating = false; if (tm.match('.')) { floating = true; if (!tm.matchDec(0, 1)) throw new ParseException(ILLEGAL_NUMBER, pointer); } if (tm.match('e') || tm.match('E')) { floating = true; tm.matchAny("-+"); // ignore the result, just step the index if (!tm.matchDec(0, 1)) throw new ParseException(ILLEGAL_NUMBER, pointer); } if (!floating) { if (integerLength < MAX_INTEGER_DIGITS_LENGTH) return tm.getResultInt(negative); try { long result = tm.getResultLong(negative); if (result >= Integer.MIN_VALUE && result <= Integer.MAX_VALUE) return (int)result; return result; } catch (NumberFormatException ignore) { // too big for Long - drop through to BigDecimal } } return new BigDecimal(tm.getString(numberStart, tm.getIndex())); } throw new ParseException(ILLEGAL_SYNTAX, pointer); } /** * Parse a JSON string from the current position of a {@link TextMatcher} (which must be positioned after the * opening double quote). The index is left positioned after the closing double quote. * * @param tm a {@link TextMatcher} * @param pointer a string in JSON Pointer syntax * describing the position in the result JSON (for use in error reporting) * @return the JSON string * @throws ParseException if there are any errors in the JSON */ private static String parseString(TextMatcher tm, String pointer) { try { return JSONFunctions.parseString(tm); } catch (IllegalArgumentException iae) { throw new ParseException(iae.getMessage(), pointer); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy